repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
sonots/activerecord-refresh_connection
https://github.com/sonots/activerecord-refresh_connection/blob/5f5a742f2feae8e5fbbce1576ef4b72d81e073e4/lib/activerecord-refresh_connection.rb
lib/activerecord-refresh_connection.rb
require 'activerecord-refresh_connection/active_record/connection_adapters/refresh_connection_management'
ruby
MIT
5f5a742f2feae8e5fbbce1576ef4b72d81e073e4
2026-01-04T17:48:56.747439Z
false
sonots/activerecord-refresh_connection
https://github.com/sonots/activerecord-refresh_connection/blob/5f5a742f2feae8e5fbbce1576ef4b72d81e073e4/lib/activerecord-refresh_connection/active_record/connection_adapters/refresh_connection_management.rb
lib/activerecord-refresh_connection/active_record/connection_adapters/refresh_connection_management.rb
module ActiveRecord module ConnectionAdapters class RefreshConnectionManagement DEFAULT_OPTIONS = {max_requests: 1} def initialize(app, options = {}) @app = app @options = DEFAULT_OPTIONS.merge(options) @mutex = Mutex.new reset_remain_count end def call(env) testing = env.key?('rack.test') response = @app.call(env) response[2] = ::Rack::BodyProxy.new(response[2]) do # disconnect all connections on the connection pool clear_connections unless testing end response rescue Exception clear_connections unless testing raise end private def clear_connections if should_clear_all_connections? ActiveRecord::Base.clear_all_connections! else ActiveRecord::Base.clear_active_connections! end end def should_clear_all_connections? return true if max_requests <= 1 @mutex.synchronize do @remain_count -= 1 (@remain_count <= 0).tap do |clear| reset_remain_count if clear end end end def reset_remain_count @remain_count = max_requests end def max_requests @options[:max_requests] end end end end
ruby
MIT
5f5a742f2feae8e5fbbce1576ef4b72d81e073e4
2026-01-04T17:48:56.747439Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/routing_spec.rb
spec/routing_spec.rb
require 'spec_helper' describe 'API Routing' do include RSpec::Rails::RequestExampleGroup describe "V1" do it "should not route something from V2" do get new_api_foo_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.myvendor+json;version=1' } expect(response.status).to eq(404) end it "should route" do get new_api_bar_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.myvendor+json;version=1' } expect(@controller.class).to eq(Api::V1::BarController) end it "should default" do get new_api_bar_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.myvendor+json' } expect(@controller.class).to eq(Api::V1::BarController) end it "should default with nothing after the semi-colon" do get new_api_bar_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.myvendor+json; ' } expect(@controller.class).to eq(Api::V1::BarController) end end describe "V2" do it "should copy bar" do get new_api_bar_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.myvendor+json;version=2' } expect(@controller.class).to eq(Api::V2::BarController) end it "should add foo" do get new_api_foo_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.myvendor+json;version=2' } expect(@controller.class).to eq(Api::V2::FooController) end it "should not default" do get new_api_foo_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.myvendor+json' } expect(response.status).to eq(404) end it "should default" do original_version = ApiVersions::VersionCheck.default_version ApiVersions::VersionCheck.default_version = 2 get new_api_foo_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.myvendor+json' } ApiVersions::VersionCheck.default_version = original_version expect(@controller.class).to eq(Api::V2::FooController) end end describe "V3" do it "should copy foo" do get new_api_foo_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.myvendor+json;version=3' } expect(@controller.class).to eq(Api::V3::FooController) end it "should route to nested controllers" do get new_api_nests_nested_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.myvendor+json;version=3' } expect(@controller.class).to eq(Api::V3::Nests::NestedController) end end describe "Header syntax" do context "when valid" do after(:each) do get new_api_bar_path, headers: { 'HTTP_ACCEPT' => @accept_string } desired_format = /application\/.*\+\s*(?<format>\w+)\s*/.match(@accept_string)[:format] expect(response.content_type).to eq("application/#{desired_format}") expect(response).to be_successful end context "the semi-colon" do it "should allow spaces after" do @accept_string = 'application/vnd.myvendor+json; version=1' end it "should allow spaces before" do @accept_string = 'application/vnd.myvendor+xml ;version=1' end it "should allow spaces around" do @accept_string = 'application/vnd.myvendor+xml ; version=1' end end context "the equal sign" do it "should allow spacing before" do @accept_string = 'application/vnd.myvendor+json; version =1' end it "should allow spacing after" do @accept_string = 'application/vnd.myvendor+json; version= 1' end it "should allow spacing around" do @accept_string = 'application/vnd.myvendor+json; version = 1' end end context "the plus sign" do it "should allow spacing before" do @accept_string = 'application/vnd.myvendor +xml; version=1' end it "should allow spacing after" do @accept_string = 'application/vnd.myvendor+ xml; version=1' end it "should allow spacing around" do @accept_string = 'application/vnd.myvendor + xml; version=1' end end end it "should not route when invalid" do get new_api_bar_path, headers: { 'HTTP_ACCEPT' => 'application/vnd.garbage+xml;version=1' } expect(response.status).to eq(404) end end describe 'paths' do it "should pass options, such as :path, to the regular routing DSL" do expect(new_api_baz_path).to eq('/baz/new') end it 'should be possible to use shallow routes with overwritten :path option' do expect(api_reply_path(1)).to eq('/replies/1') end end describe 'namespace' do it "should be possible to remove api namespace" do expect(new_qux_path).to eq('/qux/new') end it "should be possible to overwrite api namespace" do expect(new_auth_api_quux_path).to eq('/auth_api/quux/new') end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/api_versions_spec.rb
spec/api_versions_spec.rb
require 'spec_helper' describe ApiVersions do let(:testclass) { Class.new.extend ApiVersions } it "should raise if no vendor string is provided" do expect { testclass.api }.to raise_exception(RuntimeError, 'Please set a vendor_string for the api method') end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/middleware_spec.rb
spec/middleware_spec.rb
require 'spec_helper' require 'rack/test' describe ApiVersions::Middleware do let(:app) { ->(env) { [200, { "Content-Type" => "text/plain" }, [env["HTTP_ACCEPT"]]] } } around do |example| original = ApiVersions::VersionCheck.vendor_string ApiVersions::VersionCheck.vendor_string = "myvendor" example.run ApiVersions::VersionCheck.vendor_string = original end describe "the accept header" do it "should not adjust the header" do request = Rack::MockRequest.env_for("/", "HTTP_ACCEPT" => "application/vnd.foobar+json;version=1", lint: true, fatal: true) response = described_class.new(app).call(request).last expect(response.first).to eq("application/vnd.foobar+json;version=1") end it "should adjust the header" do request = Rack::MockRequest.env_for("/", "HTTP_ACCEPT" => "text/plain,application/vnd.myvendor+json;version=1,text/html,application/vnd.myvendor+xml", lint: true, fatal: true) response = described_class.new(app).call(request).last expect(response.last).to eq("text/plain,application/json,application/vnd.myvendor+json;version=1,text/html,application/xml,application/vnd.myvendor+xml") end it "should add a default vendor accept to a nil Accept header" do request = Rack::MockRequest.env_for("/", lint: true, fatal: true) response = described_class.new(app).call(request).last expect(response.last).to eq("application/json,application/vnd.#{ApiVersions::VersionCheck.vendor_string}+json") end it "should add a default vendor accept to an empty Accept header" do request = Rack::MockRequest.env_for("/", "HTTP_ACCEPT" => '', lint: true, fatal: true) response = described_class.new(app).call(request).last expect(response.last).to eq("application/json,application/vnd.#{ApiVersions::VersionCheck.vendor_string}+json") end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/spec_helper.rb
spec/spec_helper.rb
require 'coveralls' Coveralls.wear! do add_filter "/spec/" end ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../dummy/config/environment", __FILE__) require 'rspec/rails' require 'ammeter/init' Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| config.infer_base_class_for_anonymous_controllers = true config.order = "random" end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/generators/bump_generator_spec.rb
spec/generators/bump_generator_spec.rb
require 'spec_helper' require 'generators/api_versions/bump_generator' describe ApiVersions::Generators::BumpGenerator do before do destination File.expand_path("../../../tmp", __FILE__) prepare_destination end describe "Generated files" do before { run_generator } describe "Bar Controller" do subject { file('app/controllers/api/v4/bar_controller.rb') } it { is_expected.to exist } it { is_expected.to contain /Api::V4::BarController < Api::V3::BarController/ } end describe "Foo Controller" do subject { file('app/controllers/api/v4/foo_controller.rb') } it { is_expected.to exist } it { is_expected.to contain /Api::V4::FooController < Api::V3::FooController/ } end describe "Nested Controller" do subject { file('app/controllers/api/v4/nests/nested_controller.rb') } it { is_expected.to exist } it { is_expected.to contain /Api::V4::Nests::NestedController < Api::V3::Nests::NestedController/ } end describe "Users Controller" do subject { file('app/controllers/api/v4/users_controller.rb') } it { is_expected.not_to exist } end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/app/controllers/errors_controller.rb
spec/dummy/app/controllers/errors_controller.rb
class ErrorsController < ActionController::Base def not_found head :not_found end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/app/controllers/v1/qux_controller.rb
spec/dummy/app/controllers/v1/qux_controller.rb
class V1::QuxController < ActionController::Base def new respond_to do |format| format.json { render json: {} } format.xml { render xml: {} } end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/app/controllers/api/v1/bar_controller.rb
spec/dummy/app/controllers/api/v1/bar_controller.rb
class Api::V1::BarController < ActionController::Base def new respond_to do |format| format.json { render json: {} } format.xml { render xml: {} } end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/app/controllers/api/v2/foo_controller.rb
spec/dummy/app/controllers/api/v2/foo_controller.rb
class Api::V2::FooController < ActionController::Base def new respond_to do |format| format.json { render json: {} } format.xml { render xml: {} } end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/app/controllers/api/v2/users_controller.rb
spec/dummy/app/controllers/api/v2/users_controller.rb
class Api::V2::UsersController < ActionController::Base end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/app/controllers/api/v2/bar_controller.rb
spec/dummy/app/controllers/api/v2/bar_controller.rb
class Api::V2::BarController < Api::V1::BarController end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/app/controllers/api/v3/foo_controller.rb
spec/dummy/app/controllers/api/v3/foo_controller.rb
class Api::V3::FooController < Api::V2::FooController end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/app/controllers/api/v3/bar_controller.rb
spec/dummy/app/controllers/api/v3/bar_controller.rb
class Api::V3::BarController < ActionController::Base end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/app/controllers/api/v3/nests/nested_controller.rb
spec/dummy/app/controllers/api/v3/nests/nested_controller.rb
class Api::V3::Nests::NestedController < ActionController::Base def new render body: nil end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/app/controllers/auth_api/v1/quux_controller.rb
spec/dummy/app/controllers/auth_api/v1/quux_controller.rb
class AuthApi::V1::QuuxController < ActionController::Base def new respond_to do |format| format.json { render json: {} } format.xml { render xml: {} } end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/config/application.rb
spec/dummy/config/application.rb
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "action_controller/railtie" if defined?(Rails.groups) Bundler.require(*Rails.groups) else Bundler.require end require "api-versions" module Dummy class Application < Rails::Application end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/config/environment.rb
spec/dummy/config/environment.rb
# Load the rails application. require File.expand_path('../application', __FILE__) # Initialize the rails application. Dummy::Application.initialize!
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/config/routes.rb
spec/dummy/config/routes.rb
Dummy::Application.routes.draw do api vendor_string: "myvendor" do version 1 do cache as: 'v1' do resources :bar end end version 2 do cache as: 'v2' do resources :foo inherit from: 'v1' end end version 3 do inherit from: 'v2' namespace :nests do resources :nested end end end api vendor_string: 'myvendor', path: '' do version 1 do cache as: 'v1' do resources :baz end end end api vendor_string: 'myvendor', namespace: '' do version 1 do cache as: 'v1' do resources :qux end end end api vendor_string: 'myvendor', namespace: 'auth_api' do version 1 do cache as: 'v1' do resources :quux end end end api vendor_string: 'myvendor', path: '' do version 1 do cache as: 'v1' do resources :posts, shallow: true do resources :replies end end end end get '*a' => 'errors#not_found' end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/config/boot.rb
spec/dummy/config/boot.rb
gemfile = File.expand_path('../../../../Gemfile', __FILE__) if File.exist?(gemfile) ENV['BUNDLE_GEMFILE'] = gemfile require 'bundler' Bundler.setup end $:.unshift File.expand_path('../../../../lib', __FILE__)
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/spec/dummy/config/environments/test.rb
spec/dummy/config/environments/test.rb
Dummy::Application.configure do config.cache_classes = true config.eager_load = false config.consider_all_requests_local = true config.action_controller.perform_caching = false config.action_dispatch.show_exceptions = false config.action_controller.allow_forgery_protection = false config.active_support.deprecation = :stderr config.secret_key_base = "eb6e66d4263b36e93912a0e0c367059d38c3417058890737c1bed0e52961429817430c38be6acab423cf023fe51c05123727f4dd4782cb2a46966d496d8e951c" end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/lib/api-versions.rb
lib/api-versions.rb
require "api-versions/version" require "api-versions/version_check" require "api-versions/dsl" require 'api-versions/middleware' require 'api-versions/railtie' module ApiVersions def api(options = {}, &block) raise "Please set a vendor_string for the api method" if options[:vendor_string].nil? VersionCheck.default_version = options[:default_version] VersionCheck.vendor_string = options[:vendor_string] api_namespace = options.fetch(:namespace, :api) if api_namespace.blank? DSL.new(self, &block) else namespace(api_namespace, options) { DSL.new(self, &block) } end end end ActionDispatch::Routing::Mapper.send :include, ApiVersions
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/lib/generators/api_versions/bump_generator.rb
lib/generators/api_versions/bump_generator.rb
module ApiVersions module Generators class BumpGenerator < Rails::Generators::Base desc "Bump API version to next version, initializing controllers" source_root File.expand_path('../templates', __FILE__) def get_controllers Dir.chdir File.join(Rails.root, 'app', 'controllers') do @controllers = Dir.glob('api/v**/**/*.rb') end @highest_version = @controllers.map do |controller| controller.match(/api\/v(\d+?)\//)[1] end.max @controllers.keep_if { |element| element =~ /api\/v#{@highest_version}\// } end def generate_new_controllers @controllers.each do |controller| new_controller = controller.gsub(/api\/v#{@highest_version}\//, "api/v#{@highest_version.to_i + 1}/") @current_new_controller = new_controller.chomp(File.extname(controller)).camelize @current_old_controller = controller.chomp(File.extname(controller)).camelize template 'controller.rb', File.join('app', 'controllers', new_controller) end end end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/lib/generators/api_versions/templates/controller.rb
lib/generators/api_versions/templates/controller.rb
class <%= @current_new_controller %> < <%= @current_old_controller %> end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/lib/api-versions/version.rb
lib/api-versions/version.rb
module ApiVersions class Version MAJOR = 1 MINOR = 2 PATCH = 1 def self.to_s [MAJOR, MINOR, PATCH].join('.') end end VERSION = Version.to_s end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/lib/api-versions/middleware.rb
lib/api-versions/middleware.rb
module ApiVersions class Middleware def initialize(app) @app = app end def call(env) accept_string = env['HTTP_ACCEPT'] || "" accepts = accept_string.split(',') accepts.push("application/vnd.#{ApiVersions::VersionCheck.vendor_string}+json") unless accept_string.include?('application/vnd.') offset = 0 accepts.dup.each_with_index do |accept, i| accept.strip! match = /\Aapplication\/vnd\.#{ApiVersions::VersionCheck.vendor_string}\s*\+\s*(?<format>\w+)\s*/.match(accept) if match accepts.insert i + offset, "application/#{match[:format]}" offset += 1 end end env['HTTP_ACCEPT'] = accepts.join(',') @app.call(env) end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/lib/api-versions/railtie.rb
lib/api-versions/railtie.rb
require 'rails/railtie' module ApiVersions class Railtie < Rails::Railtie config.app_middleware.use ApiVersions::Middleware end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/lib/api-versions/dsl.rb
lib/api-versions/dsl.rb
require 'forwardable' module ApiVersions class DSL extend Forwardable def initialize(context, &block) @context = context singleton_class.def_delegators :@context, *(@context.public_methods - public_methods) instance_eval(&block) end def version(version_number, &block) VersionCheck.default_version ||= version_number constraints VersionCheck.new(version: version_number) do scope({ module: "v#{version_number}" }, &block) end end def inherit(options) Array.wrap(options[:from]).each do |block| @resource_cache[block].call end end def cache(options, &block) @resource_cache ||= {} @resource_cache[options[:as]] = block yield end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
EDMC/api-versions
https://github.com/EDMC/api-versions/blob/4e6f2d01369c1a82b0a1c927b0237d487cf7658c/lib/api-versions/version_check.rb
lib/api-versions/version_check.rb
module ApiVersions class VersionCheck class << self attr_accessor :default_version, :vendor_string end def initialize(args = {}) @process_version = args[:version] end def matches?(request) accepts = request.headers['Accept'].split(',') accepts.any? do |accept| accept.strip! accepts_proper_format?(accept) && (matches_version?(accept) || unversioned?(accept)) end end private def accepts_proper_format?(accept_string) accept_string =~ /\Aapplication\/vnd\.#{self.class.vendor_string}\s*\+\s*.+/ end def matches_version?(accept_string) accept_string =~ /version\s*?=\s*?#{@process_version}\b/ end def unversioned?(accept_string) @process_version == self.class.default_version && !(accept_string =~ /version\s*?=\s*?\d*\b/i) end end end
ruby
MIT
4e6f2d01369c1a82b0a1c927b0237d487cf7658c
2026-01-04T17:49:05.418211Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/hash_validator_spec_helper.rb
spec/hash_validator_spec_helper.rb
# frozen_string_literal: true module HashValidatorSpecHelper def validate(hash, validations, strict = false) HashValidator.validate(hash, validations, strict) end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/configuration_spec.rb
spec/configuration_spec.rb
# frozen_string_literal: true require "spec_helper" describe "HashValidator.configure" do describe "configuration DSL" do after(:each) do # Clean up any validators added during tests HashValidator.remove_validator("test_pattern") HashValidator.remove_validator("test_func") HashValidator.remove_validator("bulk_odd") HashValidator.remove_validator("bulk_even") HashValidator.remove_validator("bulk_palindrome") HashValidator.remove_validator("custom_configured") end it "allows adding instance-based validators" do class HashValidator::Validator::CustomConfiguredValidator < HashValidator::Validator::Base def initialize super("custom_configured") end def valid?(value) value == "configured" end end HashValidator.configure do |config| config.add_validator HashValidator::Validator::CustomConfiguredValidator.new end validator = HashValidator.validate( { status: "configured" }, { status: "custom_configured" } ) expect(validator.valid?).to eq true end it "allows adding pattern-based validators" do HashValidator.configure do |config| config.add_validator "test_pattern", pattern: /\A[A-Z]{3}\z/, error_message: "must be three uppercase letters" end validator = HashValidator.validate( { code: "ABC" }, { code: "test_pattern" } ) expect(validator.valid?).to eq true validator = HashValidator.validate( { code: "abc" }, { code: "test_pattern" } ) expect(validator.valid?).to eq false expect(validator.errors).to eq({ code: "must be three uppercase letters" }) end it "allows adding function-based validators" do HashValidator.configure do |config| config.add_validator "test_func", func: ->(v) { v.is_a?(Integer) && v > 100 }, error_message: "must be an integer greater than 100" end validator = HashValidator.validate( { score: 150 }, { score: "test_func" } ) expect(validator.valid?).to eq true validator = HashValidator.validate( { score: 50 }, { score: "test_func" } ) expect(validator.valid?).to eq false expect(validator.errors).to eq({ score: "must be an integer greater than 100" }) end it "allows adding multiple validators in one configure block" do HashValidator.configure do |config| config.add_validator "bulk_odd", pattern: /\A\d*[13579]\z/, error_message: "must be odd" config.add_validator "bulk_even", pattern: /\A\d*[02468]\z/, error_message: "must be even" config.add_validator "bulk_palindrome", func: proc { |s| s.to_s == s.to_s.reverse }, error_message: "must be a palindrome" end # Test odd validator validator = HashValidator.validate( { num: "13" }, { num: "bulk_odd" } ) expect(validator.valid?).to eq true # Test even validator validator = HashValidator.validate( { num: "24" }, { num: "bulk_even" } ) expect(validator.valid?).to eq true # Test palindrome validator validator = HashValidator.validate( { word: "level" }, { word: "bulk_palindrome" } ) expect(validator.valid?).to eq true end it "allows removing validators within configure block" do # First add a validator HashValidator.add_validator "test_pattern", pattern: /test/, error_message: "test" # Then remove it in configure HashValidator.configure do |config| config.remove_validator "test_pattern" end # Should raise error as validator no longer exists expect { HashValidator.validate({ value: "test" }, { value: "test_pattern" }) }.to raise_error(StandardError, /Could not find valid validator/) end it "works without a block" do expect { HashValidator.configure }.not_to raise_error end it "yields a Configuration instance" do HashValidator.configure do |config| expect(config).to be_a(HashValidator::Configuration) end end end describe "Rails-style initializer example" do after(:each) do HashValidator.remove_validator("phone") HashValidator.remove_validator("postal_code") HashValidator.remove_validator("age_range") end it "can be used like a Rails initializer" do # This would typically be in config/initializers/hash_validator.rb HashValidator.configure do |config| # Add pattern validators config.add_validator "phone", pattern: /\A\+?[1-9]\d{1,14}\z/, error_message: "must be a valid international phone number" config.add_validator "postal_code", pattern: /\A[A-Z0-9]{3,10}\z/i, error_message: "must be a valid postal code" # Add function validator config.add_validator "age_range", func: ->(age) { age.is_a?(Integer) && age.between?(0, 120) }, error_message: "must be between 0 and 120" end # Use the configured validators validator = HashValidator.validate( { phone: "+14155551234", postal_code: "SW1A1AA", age: 30 }, { phone: "phone", postal_code: "postal_code", age: "age_range" } ) expect(validator.valid?).to eq true expect(validator.errors).to be_empty end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/hash_validator_spec.rb
spec/hash_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator do describe "Adding validators" do let(:new_validator1) { HashValidator::Validator::SimpleValidator.new("my_type1", lambda { |v| true }) } let(:new_validator2) { HashValidator::Validator::SimpleValidator.new("my_type2", lambda { |v| true }) } it "allows validators with unique names" do expect { HashValidator.add_validator(new_validator1) }.to_not raise_error end it "does not allow validators with conflicting names" do expect { HashValidator.add_validator(new_validator2) HashValidator.add_validator(new_validator2) }.to raise_error(StandardError, "validators need to have unique names") end it "does not allow validators that do not inherit from the base validator class" do expect { HashValidator.add_validator("Not a validator") }.to raise_error(StandardError, "validators need to inherit from HashValidator::Validator::Base") end it "raises ArgumentError when options hash is missing :pattern or :func key" do expect { HashValidator.add_validator("test_validator", { invalid_key: "value" }) }.to raise_error(ArgumentError, "Options hash must contain either :pattern or :func key") end it "raises ArgumentError when second argument is not a hash" do expect { HashValidator.add_validator("test_validator", "not_a_hash") }.to raise_error(ArgumentError, "Second argument must be an options hash with :pattern or :func key") end it "raises ArgumentError when wrong number of arguments are provided" do expect { HashValidator.add_validator("test", "arg2", "arg3") }.to raise_error(ArgumentError, "add_validator expects 1 argument (validator instance) or 2 arguments (name, options)") end end describe "#validate" do describe "individual type validations" do it "should validate hash" do expect(validate({ v: {} }, { v: {} }).valid?).to eq true expect(validate({ v: "" }, { v: {} }).valid?).to eq false expect(validate({ v: "" }, { v: {} }).errors).to eq({ v: "hash required" }) end it "should validate presence" do expect(validate({ v: "test" }, { v: "required" }).valid?).to eq true expect(validate({ v: 1234 }, { v: "required" }).valid?).to eq true expect(validate({ v: nil }, { v: "required" }).valid?).to eq false expect(validate({ v: nil }, { v: "required" }).errors).to eq({ v: "is required" }) expect(validate({ x: "test" }, { v: "required" }).valid?).to eq false expect(validate({ x: "test" }, { v: "required" }).errors).to eq({ v: "is required" }) expect(validate({ x: 1234 }, { v: "required" }).valid?).to eq false expect(validate({ x: 1234 }, { v: "required" }).errors).to eq({ v: "is required" }) end it "should validate string" do expect(validate({ v: "test" }, { v: "string" }).valid?).to eq true expect(validate({ v: 123456 }, { v: "string" }).valid?).to eq false expect(validate({ v: 123456 }, { v: "string" }).errors).to eq({ v: "string required" }) end it "should validate numeric" do expect(validate({ v: 1234 }, { v: "numeric" }).valid?).to eq true expect(validate({ v: "12" }, { v: "numeric" }).valid?).to eq false end it "should validate array" do expect(validate({ v: [ 1, 2, 3 ] }, { v: "array" }).valid?).to eq true expect(validate({ v: " 1,2,3 " }, { v: "array" }).valid?).to eq false end it "should validate time" do expect(validate({ v: Time.now }, { v: "time" }).valid?).to eq true expect(validate({ v: "2013-04-12 13:18:05 +0930" }, { v: "time" }).valid?).to eq false end end describe "validator syntax" do it "should allow strings as validator names" do expect(validate({ v: "test" }, { v: "string" }).valid?).to eq true end it "should allow symbols as validator names" do expect(validate({ v: "test" }, { v: :string }).valid?).to eq true end end describe "full validations" do let(:empty_hash) { {} } let(:simple_hash) { { foo: 1, bar: "baz" }} let(:invalid_simple_hash) { { foo: 1, bar: 2 }} let(:complex_hash) { { foo: 1, bar: "baz", user: { first_name: "James", last_name: "Brooks", age: 27, likes: [ "Ruby", "Kendo", "Board Games" ] } }} let(:invalid_complex_hash) { { foo: 1, bar: 2, user: { first_name: "James", last_name: "Brooks", likes: "Ruby, Kendo, Board Games" } }} describe "no validations" do let(:validations) { {} } it "should validate an empty hash" do v = validate(empty_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end it "should validate a simple hash" do v = validate(simple_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end it "should validate a simple hash 2" do v = validate(invalid_simple_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end it "should validate a complex hash" do v = validate(complex_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end it "should validate a complex hash 2" do v = validate(invalid_complex_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end end describe "simple validations" do let(:validations) { { foo: "numeric", bar: "string" } } it "should not validate an empty hash (stating missing with required)" do v = validate(empty_hash, validations) expect(v.valid?).to eq false expect(v.errors).to eq({ foo: "numeric required", bar: "string required" }) end it "should validate a simple hash" do v = validate(simple_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end it "should not validate a simple hash 2" do v = validate(invalid_simple_hash, validations) expect(v.valid?).to eq false expect(v.errors).to eq({ bar: "string required" }) end it "should validate a complex hash" do v = validate(complex_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end it "should not validate a complex hash 2" do v = validate(invalid_complex_hash, validations) expect(v.valid?).to eq false expect(v.errors).to eq({ bar: "string required" }) end end describe "nested validations" do let(:validations) { { foo: "numeric", bar: "string", user: { first_name: "string", last_name: /^(Brooks|Smith)$/, age: "required", likes: "array" } }} it "should validate a complex hash" do v = validate(complex_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end it "should not validate a complex hash 2" do v = validate(invalid_complex_hash, validations) expect(v.valid?).to eq false expect(v.errors).to eq({ bar: "string required", user: { age: "is required", likes: "array required" } }) end end describe "optional validations" do let(:validations) { { foo: "numeric", bar: HashValidator.optional("string") } } it "should validate a complex hash" do v = validate(complex_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end it "should not validate a complex hash 2" do v = validate(invalid_complex_hash, validations) expect(v.valid?).to eq false expect(v.errors).to eq({ bar: "string required" }) end end describe "many validations" do let(:validations) { { foo: "numeric", bar: "string", user: { first_name: "string", likes: HashValidator.many("string") } } } it "should validate a complex hash" do v = validate(complex_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end it "should not validate a complex hash 2" do v = validate(invalid_complex_hash, validations) expect(v.valid?).to eq false expect(v.errors).to eq({ bar: "string required", user: { likes: "enumerable required" } }) end end describe "multiple validations" do let(:validations) { { foo: "numeric", user: { age: HashValidator.multiple("numeric", 1..100) } } } it "should validate a complex hash" do v = validate(complex_hash, validations) expect(v.valid?).to eq true expect(v.errors).to be_empty end it "should not validate a complex hash 2" do v = validate(invalid_complex_hash, validations) expect(v.valid?).to eq false expect(v.errors).to eq({ user: { age: "numeric required, value from list required" } }) end end end end end describe "Strict Validation" do let(:simple_hash) { { foo: "bar", bar: "foo" } } let(:complex_hash) { { foo: 1, user: { first_name: "James", last_name: "Brooks", age: 27, likes: [ "Ruby", "Kendo", "Board Games" ] } }} let(:validations) { { foo: "string" } } let(:complex_validations) { { foo: "integer", user: { first_name: "string", age: "integer" } }} it "reports which keys are not expected for a simple hash" do v = validate(simple_hash, validations, true) expect(v.valid?).to eq false expect(v.errors).to eq({ bar: "key not expected" }) end it "reports which keys are not expected for a complex hash" do v = validate(complex_hash, complex_validations, true) expect(v.valid?).to eq false expect(v.errors).to eq(user: { last_name: "key not expected", likes: "key not expected" }) end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require "rubygems" require "simplecov" require "simplecov_json_formatter" SimpleCov.start do formatter SimpleCov::Formatter::JSONFormatter add_filter "/spec/" end require "hash_validator" require "hash_validator_spec_helper" RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus config.order = "random" config.include HashValidatorSpecHelper end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/ip_validator_spec.rb
spec/validators/ip_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::IpValidator do let(:validator) { HashValidator::Validator::IpValidator.new } context "valid IP addresses" do it "validates IPv4 addresses" do errors = {} validator.validate("key", "192.168.1.1", {}, errors) expect(errors).to be_empty end it "validates IPv4 localhost" do errors = {} validator.validate("key", "127.0.0.1", {}, errors) expect(errors).to be_empty end it "validates IPv4 zero address" do errors = {} validator.validate("key", "0.0.0.0", {}, errors) expect(errors).to be_empty end it "validates IPv4 broadcast address" do errors = {} validator.validate("key", "255.255.255.255", {}, errors) expect(errors).to be_empty end it "validates IPv6 addresses" do errors = {} validator.validate("key", "2001:db8:85a3::8a2e:370:7334", {}, errors) expect(errors).to be_empty end it "validates IPv6 localhost" do errors = {} validator.validate("key", "::1", {}, errors) expect(errors).to be_empty end it "validates IPv6 zero address" do errors = {} validator.validate("key", "::", {}, errors) expect(errors).to be_empty end it "validates IPv4-mapped IPv6 addresses" do errors = {} validator.validate("key", "::ffff:192.168.1.1", {}, errors) expect(errors).to be_empty end end context "invalid IP addresses" do it "rejects non-string values" do errors = {} validator.validate("key", 123, {}, errors) expect(errors["key"]).to eq("is not a valid IP address") end it "rejects nil values" do errors = {} validator.validate("key", nil, {}, errors) expect(errors["key"]).to eq("is not a valid IP address") end it "rejects malformed IPv4 addresses" do errors = {} validator.validate("key", "256.1.1.1", {}, errors) expect(errors["key"]).to eq("is not a valid IP address") end it "rejects malformed IPv6 addresses" do errors = {} validator.validate("key", "2001:db8:85a3::8a2e::7334", {}, errors) expect(errors["key"]).to eq("is not a valid IP address") end it "rejects non-IP strings" do errors = {} validator.validate("key", "not an ip", {}, errors) expect(errors["key"]).to eq("is not a valid IP address") end it "rejects empty strings" do errors = {} validator.validate("key", "", {}, errors) expect(errors["key"]).to eq("is not a valid IP address") end it "rejects hostnames" do errors = {} validator.validate("key", "example.com", {}, errors) expect(errors["key"]).to eq("is not a valid IP address") end it "rejects URLs" do errors = {} validator.validate("key", "http://192.168.1.1", {}, errors) expect(errors["key"]).to eq("is not a valid IP address") end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/multiple_spec.rb
spec/validators/multiple_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::Base do let(:validator) { HashValidator::Validator::MultipleValidator.new } let(:errors) { Hash.new } def multiple(*validations) HashValidator::Validations::Multiple.new(validations) end describe "#should_validate?" do it "should validate an Multiple validation" do expect(validator.should_validate?(multiple("numeric", 1..10))).to eq true end it "should not validate other things" do expect(validator.should_validate?("string")).to eq false expect(validator.should_validate?("array")).to eq false expect(validator.should_validate?(nil)).to eq false end end describe "#validate" do it "should accept an empty collection of validators" do validator.validate(:key, 73, multiple(), errors) expect(errors).to be_empty end it "should accept an collection of validators" do validator.validate(:key, 73, multiple("numeric", 1..100), errors) expect(errors).to be_empty end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/simple_spec.rb
spec/validators/simple_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::SimpleValidator do describe "#initialize" do it "accepts blocks with one argument" do expect { HashValidator::Validator::SimpleValidator.new("name", lambda { |a| true }) }.to_not raise_error end it "does not accept blocks with no arguments" do expect { HashValidator::Validator::SimpleValidator.new("name", lambda { true }) }.to raise_error(StandardError, "lambda should take only one argument - passed lambda takes 0") end it "does not accept blocks with two arguments" do expect { HashValidator::Validator::SimpleValidator.new("name", lambda { |a, b| true }) }.to raise_error(StandardError, "lambda should take only one argument - passed lambda takes 2") end end describe "#validate" do # Lambda that accepts strings that are 4 characters or shorter let(:short_string_lambda) { lambda { |v| v.is_a?(String) && v.size < 5 } } let(:short_string_validator) { HashValidator::Validator::SimpleValidator.new("short_string", short_string_lambda) } let(:errors) { Hash.new } [ "", "1", "12", "123", "1234" ].each do |value| it "validates the string '#{value}'" do short_string_validator.validate(:key, value, {}, errors) expect(errors).to be_empty end end [ nil, "12345", "123456", 123, 123456, Time.now, (1..5) ].each do |value| it "does not validate bad value '#{value}'" do short_string_validator.validate(:key, value, {}, errors) expect(errors).to eq({ key: "short_string required" }) end end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/alpha_validator_spec.rb
spec/validators/alpha_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::AlphaValidator do let(:validator) { HashValidator::Validator::AlphaValidator.new } context "valid alpha strings" do it "validates lowercase letters" do errors = {} validator.validate("key", "abc", {}, errors) expect(errors).to be_empty end it "validates uppercase letters" do errors = {} validator.validate("key", "ABC", {}, errors) expect(errors).to be_empty end it "validates mixed case letters" do errors = {} validator.validate("key", "AbC", {}, errors) expect(errors).to be_empty end it "validates single letter" do errors = {} validator.validate("key", "a", {}, errors) expect(errors).to be_empty end it "validates long strings" do errors = {} validator.validate("key", "HelloWorld", {}, errors) expect(errors).to be_empty end end context "invalid alpha strings" do it "rejects non-string values" do errors = {} validator.validate("key", 123, {}, errors) expect(errors["key"]).to eq("must contain only letters") end it "rejects nil values" do errors = {} validator.validate("key", nil, {}, errors) expect(errors["key"]).to eq("must contain only letters") end it "rejects strings with numbers" do errors = {} validator.validate("key", "abc123", {}, errors) expect(errors["key"]).to eq("must contain only letters") end it "rejects strings with spaces" do errors = {} validator.validate("key", "abc def", {}, errors) expect(errors["key"]).to eq("must contain only letters") end it "rejects strings with special characters" do errors = {} validator.validate("key", "abc!", {}, errors) expect(errors["key"]).to eq("must contain only letters") end it "rejects strings with hyphens" do errors = {} validator.validate("key", "abc-def", {}, errors) expect(errors["key"]).to eq("must contain only letters") end it "rejects strings with underscores" do errors = {} validator.validate("key", "abc_def", {}, errors) expect(errors["key"]).to eq("must contain only letters") end it "rejects empty strings" do errors = {} validator.validate("key", "", {}, errors) expect(errors["key"]).to eq("must contain only letters") end it "rejects strings with periods" do errors = {} validator.validate("key", "abc.def", {}, errors) expect(errors["key"]).to eq("must contain only letters") end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/in_enumerable_spec.rb
spec/validators/in_enumerable_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Enumerable validator" do describe "Accepting Enumerables in validations" do it "should accept an empty array" do validate({}, { foo: [] }) end it "should accept an array" do validate({}, { foo: [ "apple", "banana", "carrot" ] }) end it "should accept a hash" do validate({}, { foo: { apple: "apple", banana: "banana", carrot: "cattot" } }) end end describe "#validate" do describe "Simple Array" do let(:validations) { { fruit: [ "apple", "banana", "carrot" ] } } it "should validate true if the value is present" do expect(validate({ fruit: "apple" }, validations).valid?).to eq true end it "should validate false if the value is not present" do expect(validate({ fruit: "pear" }, validations).valid?).to eq false end it "should validate false if the key is not present" do expect(validate({ something: "apple" }, validations).valid?).to eq false end it "should provide an appropriate error message is the value is not present" do expect(validate({ fruit: "pear" }, validations).errors).to eq({ fruit: "value from list required" }) end end describe "Range" do let(:validations) { { number: 1..10 } } it "should validate true if the value is present" do expect(validate({ number: 5 }, validations).valid?).to eq true end it "should validate false if the value is not present" do expect(validate({ number: 15 }, validations).valid?).to eq false end end describe "Infinite Range" do let(:validations) { { number: 1..Float::INFINITY } } it "should validate true if the value is present" do expect(validate({ number: 5 }, validations).valid?).to eq true end it "should validate false if the value is not present" do expect(validate({ number: -5 }, validations).valid?).to eq false end end describe "nil values" do let(:validations) { { fruit: [ nil, :apple, :banana ] } } it "should validate true if a nil value is present" do expect(validate({ fruit: nil }, validations).valid?).to eq true end end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/digits_validator_spec.rb
spec/validators/digits_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::DigitsValidator do let(:validator) { HashValidator::Validator::DigitsValidator.new } context "valid digit strings" do it "validates single digit" do errors = {} validator.validate("key", "1", {}, errors) expect(errors).to be_empty end it "validates multiple digits" do errors = {} validator.validate("key", "123", {}, errors) expect(errors).to be_empty end it "validates zero" do errors = {} validator.validate("key", "0", {}, errors) expect(errors).to be_empty end it "validates long number strings" do errors = {} validator.validate("key", "1234567890", {}, errors) expect(errors).to be_empty end it "validates leading zeros" do errors = {} validator.validate("key", "0123", {}, errors) expect(errors).to be_empty end end context "invalid digit strings" do it "rejects non-string values" do errors = {} validator.validate("key", 123, {}, errors) expect(errors["key"]).to eq("must contain only digits") end it "rejects nil values" do errors = {} validator.validate("key", nil, {}, errors) expect(errors["key"]).to eq("must contain only digits") end it "rejects strings with letters" do errors = {} validator.validate("key", "123abc", {}, errors) expect(errors["key"]).to eq("must contain only digits") end it "rejects strings with spaces" do errors = {} validator.validate("key", "123 456", {}, errors) expect(errors["key"]).to eq("must contain only digits") end it "rejects strings with special characters" do errors = {} validator.validate("key", "123!", {}, errors) expect(errors["key"]).to eq("must contain only digits") end it "rejects strings with hyphens" do errors = {} validator.validate("key", "123-456", {}, errors) expect(errors["key"]).to eq("must contain only digits") end it "rejects strings with periods" do errors = {} validator.validate("key", "123.456", {}, errors) expect(errors["key"]).to eq("must contain only digits") end it "rejects empty strings" do errors = {} validator.validate("key", "", {}, errors) expect(errors["key"]).to eq("must contain only digits") end it "rejects negative signs" do errors = {} validator.validate("key", "-123", {}, errors) expect(errors["key"]).to eq("must contain only digits") end it "rejects positive signs" do errors = {} validator.validate("key", "+123", {}, errors) expect(errors["key"]).to eq("must contain only digits") end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/email_spec.rb
spec/validators/email_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::Base do let(:validator) { HashValidator::Validator::EmailValidator.new } let(:errors) { Hash.new } describe "#should_validate?" do it 'should validate the name "email"' do expect(validator.should_validate?("email")).to eq true end it "should not validate other names" do expect(validator.should_validate?("string")).to eq false expect(validator.should_validate?("array")).to eq false expect(validator.should_validate?(nil)).to eq false end end describe "#validate" do it "should validate an email with true" do validator.validate(:key, "johndoe@gmail.com", {}, errors) expect(errors).to be_empty end it "should validate a string without an @ symbol with false" do validator.validate(:key, "test", {}, errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "is not a valid email" }) end it "should validate a number with false" do validator.validate(:key, 123, {}, errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "is not a valid email" }) end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/array_spec.rb
spec/validators/array_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Array validator" do let(:validator) { HashValidator::Validator::ArrayValidator.new } let(:errors) { Hash.new } describe "#should_validate?" do it 'should validate the array with first item ":array"' do expect(validator.should_validate?([:array])).to eq true end it "should validate the array with empty specification" do expect(validator.should_validate?([:array, {}])).to eq true end it "should validate the array with size specified to nil" do expect(validator.should_validate?([:array, { size: nil }])).to eq true end it "should validate the array with non-sense specification" do expect(validator.should_validate?([:array, { blah_blah_blah: false }])).to eq true end it "should not validate the empty array" do expect(validator.should_validate?([])).to eq false end it "should not validate the array with nil item" do expect(validator.should_validate?([nil])).to eq false end it "should not validate other names" do expect(validator.should_validate?("string")).to eq false expect(validator.should_validate?("array")).to eq false expect(validator.should_validate?(nil)).to eq false end end describe "#validate" do it "should validate an empty array with true" do validator.validate(:key, [], [:array], errors) expect(errors).to be_empty end it "should validate an empty array with nil spec" do validator.validate(:key, [], [:array, nil], errors) expect(errors).to be_empty end it "should validate an empty array with empty spec" do validator.validate(:key, [], [:array, {}], errors) expect(errors).to be_empty end it "should validate an empty array with size spec = nil" do validator.validate(:key, [], [:array, { size: nil }], errors) expect(errors).to be_empty end it "should validate an empty array with size spec = 0" do validator.validate(:key, [], [:array, { size: 0 }], errors) expect(errors).to be_empty end it "should validate an empty array with spec = 0" do validator.validate(:key, [], [:array, 0], errors) expect(errors).to be_empty end it "should validate an empty array with spec = 0.0" do validator.validate(:key, [], [:array, 0.0], errors) expect(errors).to be_empty end it "should validate an array of one item with spec = 1" do validator.validate(:key, [nil], [:array, 1], errors) expect(errors).to be_empty end it "should validate an array of five items with {size: 5.0}" do my_array = ["one", 2, nil, ["f", "o", "u", "r"], { five: 5 }] validator.validate(:key, my_array, [:array, { size: 5.0 }], errors) expect(errors).to be_empty end # >>> NOT >>> it "should not validate non array value" do validator.validate(:key, "I'm not array", [:array], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "Array required" }) end it "should not validate an empty array with size spec = 1" do validator.validate(:key, [], [:array, { size: 1 }], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "The required size of array is 1 but is 0." }) end it "should not validate an empty array with size spec = 1" do validator.validate(:key, [], [:array, { size: 1 }], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "The required size of array is 1 but is 0." }) end it "should not validate an empty array with spec = 1" do validator.validate(:key, [], [:array, 1], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "The required size of array is 1 but is 0." }) end it 'should not validate an empty array with spec = "0" (string)' do validator.validate(:key, [], [:array, "0"], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "Second item of array specification must be Hash or Numeric." }) end it 'should not validate an empty array with spec = "1" (string)' do validator.validate(:key, [], [:array, "1"], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "Second item of array specification must be Hash or Numeric." }) end it "should not validate an empty array with {min_size: 0} spec" do validator.validate(:key, [], [:array, { min_size: 0 }], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "Not supported specification for array: min_size." }) end it "should not validate an empty array with {min_size: 0, max_size: 2} spec" do validator.validate(:key, [], [:array, { min_size: 0, max_size: 2 }], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "Not supported specification for array: max_size, min_size." }) end it "should not validate an array of four items with {size: 3} spec" do validator.validate(:key, [0, 1, 2, 3], [:array, { size: 3 }], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "The required size of array is 3 but is 4." }) end it "should not validate an array of four items with {size: 5} spec" do validator.validate(:key, [0, 1, 2, 3], [:array, { size: 5 }], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "The required size of array is 5 but is 4." }) end it "should not validate an empty array with invalid specification" do validator.validate(:key, [], [:blah], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "Wrong array specification. The array is expected as first item." }) end it "should not validate an empty array with to large specification" do validator.validate(:key, [], [:array, 0, "overlaping item"], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "Wrong size of array specification. Allowed is one or two items." }) end # Edge cases that would trigger the original 'object' variable bug it "should handle String size specification (non-empty)" do validator.validate(:key, ["item"], [:array, { size: "non-empty" }], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "The required size of array is non-empty but is 1." }) end it "should handle empty String size specification" do validator.validate(:key, [], [:array, { size: "" }], errors) expect(errors).to be_empty end it "should handle whitespace-only String size specification" do validator.validate(:key, [], [:array, { size: " " }], errors) expect(errors).to be_empty end it "should handle Array size specification (non-empty)" do validator.validate(:key, ["item"], [:array, { size: [1, 2, 3] }], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "The required size of array is [1, 2, 3] but is 1." }) end it "should handle empty Array size specification" do validator.validate(:key, [], [:array, { size: [] }], errors) expect(errors).to be_empty end it "should handle Hash size specification (non-empty)" do size_spec = { a: 1 } validator.validate(:key, ["item"], [:array, { size: size_spec }], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "The required size of array is #{size_spec.inspect} but is 1." }) end it "should handle empty Hash size specification" do validator.validate(:key, [], [:array, { size: {} }], errors) expect(errors).to be_empty end it "should handle Symbol size specification using boolean coercion" do validator.validate(:key, ["item"], [:array, { size: :symbol }], errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "The required size of array is symbol but is 1." }) end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/many_spec.rb
spec/validators/many_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::Base do let(:validator) { HashValidator::Validator::ManyValidator.new } let(:errors) { Hash.new } def many(validation) HashValidator::Validations::Many.new(validation) end describe "#should_validate?" do it "should validate an Many validation" do expect(validator.should_validate?(many("string"))).to eq true end it "should not validate other things" do expect(validator.should_validate?("string")).to eq false expect(validator.should_validate?("array")).to eq false expect(validator.should_validate?(nil)).to eq false end end describe "#validate" do it "should accept an empty array" do validator.validate(:key, [], many("string"), errors) expect(errors).to be_empty end it "should accept an array of matching elements" do validator.validate(:key, ["a", "b"], many("string"), errors) expect(errors).to be_empty end it "should not accept an array including a non-matching element" do validator.validate(:key, ["a", 2], many("string"), errors) expect(errors).to eq({ key: [nil, "string required"] }) end it "should accept an array of matching hashes" do validator.validate(:key, [{ v: "a" }, { v: "b" }], many({ v: "string" }), errors) expect(errors).to be_empty end it "should not accept an array including a non-matching element" do validator.validate(:key, [{ v: "a" }, { v: 2 }], many({ v: "string" }), errors) expect(errors).to eq({ key: [nil, { v: "string required" }] }) end it "should not accept a non-enumerable" do validator.validate(:key, "a", many({ v: "string" }), errors) expect(errors).to eq({ key: "enumerable required" }) end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/class_spec.rb
spec/validators/class_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Class validator" do let(:errors) { Hash.new } { Array => { valid: [ [], [1], ["foo"], [1, ["foo"], Time.now] ], invalid: [ nil, "", 123, "123", Time.now, "[1]" ] }, Complex => { valid: [ Complex(1), Complex(2, 3), Complex("2/3+3/4i"), 0.3.to_c ], invalid: [ nil, "", 123, "123", Time.now, "[1]", [1], "2/3+3/4i", Rational(2, 3) ] }, Float => { valid: [ 0.0, 1.1, 1.23, Float::INFINITY, Float::EPSILON ], invalid: [ nil, "", 0, 123, "123", Time.now, "[1]", "2013-03-04" ] }, Integer => { valid: [ 0, -1000000, 1000000 ], invalid: [ nil, "", 1.1, "123", Time.now, "[1]", "2013-03-04" ] }, Numeric => { valid: [ 0, 123, 123.45 ], invalid: [ nil, "", "123", Time.now ] }, Range => { valid: [ 0..10, "a".."z", 5..0 ], invalid: [ nil, "", "123", Time.now ] }, Rational => { valid: [ Rational(1), Rational(2, 3), 3.to_r ], invalid: [ nil, "", 123, "123", Time.now, "[1]", [1], Complex(2, 3) ] }, Regexp => { valid: [ /[a-z]+/, //, //i, Regexp.new(".*") ], invalid: [ nil, "", 123, "123", Time.now, ".*" ] }, String => { valid: [ "", "Hello World", "12345" ], invalid: [ nil, 12345, Time.now ] }, Symbol => { valid: [ :foo, :'', "bar".to_sym ], invalid: [ nil, "", 1.1, "123", Time.now, "[1]", "2013-03-04" ] }, Time => { valid: [ Time.now ], invalid: [ nil, "", 123, "123", "#{Time.now}" ] } }.each do |type, data| describe type do data[:valid].each do |value| it "validates '#{value}' successful" do validator = HashValidator.validate({ v: value }, { v: type }) expect(validator.valid?).to eq true expect(validator.errors).to be_empty end end data[:invalid].each do |value| it "validates '#{value}' with failure" do validator = HashValidator.validate({ v: value }, { v: type }) expect(validator.valid?).to eq false expect(validator.errors).to eq({ v: "#{type} required" }) end end end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/presence_spec.rb
spec/validators/presence_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::Base do let(:validator) { HashValidator::Validator::PresenceValidator.new } let(:errors) { Hash.new } describe "#should_validate?" do it 'should validate the name "required"' do expect(validator.should_validate?("required")).to eq true end it "should not validate other names" do expect(validator.should_validate?("string")).to eq false expect(validator.should_validate?("array")).to eq false expect(validator.should_validate?(nil)).to eq false end end describe "#validate" do it "should validate a string with true" do validator.validate(:key, "test", {}, errors) expect(errors).to be_empty end it "should validate a number with true" do validator.validate(:key, 123, {}, errors) expect(errors).to be_empty end it "should validate a time with true" do validator.validate(:key, Time.now, {}, errors) expect(errors).to be_empty end it "should validate nil with false" do validator.validate(:key, nil, {}, errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "is required" }) end it "should validate false with true" do validator.validate(:key, false, {}, errors) expect(errors).to be_empty end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/ipv6_validator_spec.rb
spec/validators/ipv6_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::Ipv6Validator do let(:validator) { HashValidator::Validator::Ipv6Validator.new } context "valid IPv6 addresses" do it "validates full IPv6 addresses" do errors = {} validator.validate("key", "2001:0db8:85a3:0000:0000:8a2e:0370:7334", {}, errors) expect(errors).to be_empty end it "validates compressed IPv6 addresses" do errors = {} validator.validate("key", "2001:db8:85a3::8a2e:370:7334", {}, errors) expect(errors).to be_empty end it "validates IPv6 localhost" do errors = {} validator.validate("key", "::1", {}, errors) expect(errors).to be_empty end it "validates IPv6 zero address" do errors = {} validator.validate("key", "::", {}, errors) expect(errors).to be_empty end it "validates IPv6 with leading zeros" do errors = {} validator.validate("key", "2001:0db8::0001", {}, errors) expect(errors).to be_empty end it "validates IPv6 with mixed case" do errors = {} validator.validate("key", "2001:DB8::1", {}, errors) expect(errors).to be_empty end it "validates IPv4-mapped IPv6 addresses" do errors = {} validator.validate("key", "::ffff:192.168.1.1", {}, errors) expect(errors).to be_empty end end context "invalid IPv6 addresses" do it "rejects non-string values" do errors = {} validator.validate("key", 123, {}, errors) expect(errors["key"]).to eq("is not a valid IPv6 address") end it "rejects nil values" do errors = {} validator.validate("key", nil, {}, errors) expect(errors["key"]).to eq("is not a valid IPv6 address") end it "rejects IPv4 addresses" do errors = {} validator.validate("key", "192.168.1.1", {}, errors) expect(errors["key"]).to eq("is not a valid IPv6 address") end it "rejects malformed IPv6 addresses" do errors = {} validator.validate("key", "2001:db8:85a3::8a2e::7334", {}, errors) expect(errors["key"]).to eq("is not a valid IPv6 address") end it "rejects too many groups" do errors = {} validator.validate("key", "2001:0db8:85a3:0000:0000:8a2e:0370:7334:extra", {}, errors) expect(errors["key"]).to eq("is not a valid IPv6 address") end it "rejects invalid characters" do errors = {} validator.validate("key", "2001:db8:85a3::8a2g:370:7334", {}, errors) expect(errors["key"]).to eq("is not a valid IPv6 address") end it "rejects empty strings" do errors = {} validator.validate("key", "", {}, errors) expect(errors["key"]).to eq("is not a valid IPv6 address") end it "rejects incomplete addresses" do errors = {} validator.validate("key", "2001:db8:", {}, errors) expect(errors["key"]).to eq("is not a valid IPv6 address") end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/simple_types_spec.rb
spec/validators/simple_types_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Simple validator types" do let(:errors) { Hash.new } # Simple types { array: { valid: [ [], [1], ["foo"], [1, ["foo"], Time.now] ], invalid: [ nil, "", 123, "123", Time.now, "[1]" ] }, complex: { valid: [ Complex(1), Complex(2, 3), Complex("2/3+3/4i"), 0.3.to_c ], invalid: [ nil, "", 123, "123", Time.now, "[1]", [1], "2/3+3/4i", Rational(2, 3) ] }, enumerable: { valid: [ [], [ 1, 2, 3 ], 1..Float::INFINITY ], invalid: [ nil, "", 123, "123", Time.now, Float::INFINITY ] }, float: { valid: [ 0.0, 1.1, 1.23, Float::INFINITY, Float::EPSILON ], invalid: [ nil, "", 0, 123, "123", Time.now, "[1]", "2013-03-04" ] }, integer: { valid: [ 0, -1000000, 1000000 ], invalid: [ nil, "", 1.1, "123", Time.now, "[1]", "2013-03-04" ] }, numeric: { valid: [ 0, 123, 123.45 ], invalid: [ nil, "", "123", Time.now ] }, range: { valid: [ 0..10, "a".."z", 5..0 ], invalid: [ nil, "", "123", Time.now ] }, rational: { valid: [ Rational(1), Rational(2, 3), 3.to_r ], invalid: [ nil, "", 123, "123", Time.now, "[1]", [1], Complex(2, 3) ] }, regexp: { valid: [ /[a-z]+/, //, //i, Regexp.new(".*") ], invalid: [ nil, "", 123, "123", Time.now, ".*" ] }, string: { valid: [ "", "Hello World", "12345" ], invalid: [ nil, 12345, Time.now ] }, symbol: { valid: [ :foo, :'', "bar".to_sym ], invalid: [ nil, "", 1.1, "123", Time.now, "[1]", "2013-03-04" ] }, time: { valid: [ Time.now ], invalid: [ nil, "", 123, "123", "#{Time.now}" ] } }.each do |type, data| describe type do data[:valid].each do |value| it "validates '#{value}' successful" do validator = HashValidator.validate({ v: value }, { v: type.to_s }) expect(validator.valid?).to eq true expect(validator.errors).to be_empty end end data[:invalid].each do |value| it "validates '#{value}' with failure" do validator = HashValidator.validate({ v: value }, { v: type.to_s }) expect(validator.valid?).to eq false expect(validator.errors).to eq({ v: "#{type} required" }) end end end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/optional_spec.rb
spec/validators/optional_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::Base do let(:validator) { HashValidator::Validator::OptionalValidator.new } let(:errors) { Hash.new } def optional(validation) HashValidator::Validations::Optional.new(validation) end describe "#should_validate?" do it "should validate an Optional validation" do expect(validator.should_validate?(optional("string"))).to eq true end it "should not validate other things" do expect(validator.should_validate?("string")).to eq false expect(validator.should_validate?("array")).to eq false expect(validator.should_validate?(nil)).to eq false end end describe "#validate" do it "should accept a missing value" do validator.validate(:key, nil, optional("string"), errors) expect(errors).to be_empty end it "should accept a present, matching value" do validator.validate(:key, "foo", optional("string"), errors) expect(errors).to be_empty end it "should reject a present, non-matching value" do validator.validate(:key, 123, optional("string"), errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "string required" }) end it "should accept a present, matching hash" do validator.validate(:key, { v: "foo" }, optional({ v: "string" }), errors) expect(errors).to be_empty end it "should reject a present, non-matching hash" do validator.validate(:key, {}, optional({ v: "string" }), errors) expect(errors).not_to be_empty expect(errors).to eq({ key: { v: "string required" } }) end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/hex_color_validator_spec.rb
spec/validators/hex_color_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::HexColorValidator do let(:validator) { HashValidator::Validator::HexColorValidator.new } context "valid hex colors" do it "validates 6-digit hex colors (lowercase)" do errors = {} validator.validate("key", "#ff0000", {}, errors) expect(errors).to be_empty end it "validates 6-digit hex colors (uppercase)" do errors = {} validator.validate("key", "#FF0000", {}, errors) expect(errors).to be_empty end it "validates 6-digit hex colors (mixed case)" do errors = {} validator.validate("key", "#Ff0000", {}, errors) expect(errors).to be_empty end it "validates 3-digit hex colors (lowercase)" do errors = {} validator.validate("key", "#f00", {}, errors) expect(errors).to be_empty end it "validates 3-digit hex colors (uppercase)" do errors = {} validator.validate("key", "#F00", {}, errors) expect(errors).to be_empty end it "validates black color" do errors = {} validator.validate("key", "#000000", {}, errors) expect(errors).to be_empty end it "validates white color" do errors = {} validator.validate("key", "#ffffff", {}, errors) expect(errors).to be_empty end it "validates complex hex colors" do errors = {} validator.validate("key", "#3a7bd4", {}, errors) expect(errors).to be_empty end end context "invalid hex colors" do it "rejects non-string values" do errors = {} validator.validate("key", 123, {}, errors) expect(errors["key"]).to eq("is not a valid hex color") end it "rejects nil values" do errors = {} validator.validate("key", nil, {}, errors) expect(errors["key"]).to eq("is not a valid hex color") end it "rejects hex colors without hash" do errors = {} validator.validate("key", "ff0000", {}, errors) expect(errors["key"]).to eq("is not a valid hex color") end it "rejects invalid length (4 digits)" do errors = {} validator.validate("key", "#ff00", {}, errors) expect(errors["key"]).to eq("is not a valid hex color") end it "rejects invalid length (5 digits)" do errors = {} validator.validate("key", "#ff000", {}, errors) expect(errors["key"]).to eq("is not a valid hex color") end it "rejects invalid length (7 digits)" do errors = {} validator.validate("key", "#ff00000", {}, errors) expect(errors["key"]).to eq("is not a valid hex color") end it "rejects invalid characters" do errors = {} validator.validate("key", "#gg0000", {}, errors) expect(errors["key"]).to eq("is not a valid hex color") end it "rejects empty strings" do errors = {} validator.validate("key", "", {}, errors) expect(errors["key"]).to eq("is not a valid hex color") end it "rejects just hash symbol" do errors = {} validator.validate("key", "#", {}, errors) expect(errors["key"]).to eq("is not a valid hex color") end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/user_defined_spec.rb
spec/validators/user_defined_spec.rb
# frozen_string_literal: true require "spec_helper" describe "User-defined validator" do let(:validator) do unless defined?(HashValidator::Validator::OddValidator) # Define our custom validator class HashValidator::Validator::OddValidator < HashValidator::Validator::Base def initialize super("odd") end def validate(key, value, validations, errors) unless value.is_a?(Integer) && value.odd? errors[key] = error_message end end end end HashValidator::Validator::OddValidator.new end let(:errors) { Hash.new } describe "#should_validate?" do it 'validates the name "odd"' do expect(validator.should_validate?("odd")).to eq true end it "does not validate other names" do expect(validator.should_validate?("string")).to eq false expect(validator.should_validate?("array")).to eq false expect(validator.should_validate?(nil)).to eq false end end describe "#validate" do it "validates odd integers with true" do validator.validate(:key, 1, {}, errors) expect(errors).to be_empty end it "validates even integers with errrors" do validator.validate(:key, 2, {}, errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "odd required" }) end it "validates even floats with errrors" do validator.validate(:key, 2.0, {}, errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "odd required" }) end it "validates odd floats with errrors" do validator.validate(:key, 1.0, {}, errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "odd required" }) end it "validates an odd integer string with errrors" do validator.validate(:key, "1", {}, errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "odd required" }) end end describe "Integrating with the entire validation system" do before { HashValidator.add_validator(validator) rescue nil } # rescue to prevent: validators need to have unique names it "can be looked up using #validator_for" do expect(HashValidator.validator_for("odd")).to be_a_kind_of(HashValidator::Validator::OddValidator) end it "can be used in validations - test 1" do validator = HashValidator.validate({ age: 27 }, { age: "odd" }) expect(validator.valid?).to eq true expect(validator.errors).to be_empty end it "can be used in validations - test 2" do validator = HashValidator.validate({ age: 40 }, { age: "odd" }) expect(validator.valid?).to eq false expect(validator.errors).to eq({ age: "odd required" }) end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/hash_validator_spec.rb
spec/validators/hash_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe "ActionController::Parameters support" do # Mock ActionController::Parameters for testing let(:mock_params_class) do Class.new do attr_reader :data def initialize(data) @data = data end def [](key) @data[key] end def keys @data.keys end def to_unsafe_h @data end def is_a?(klass) return true if klass.name == "ActionController::Parameters" super end def class Struct.new(:name).new("ActionController::Parameters") end end end before do # Define ActionController::Parameters constant for testing unless defined?(ActionController::Parameters) ActionController = Module.new unless defined?(ActionController) ActionController.const_set(:Parameters, mock_params_class) end end it "should validate ActionController::Parameters objects" do params = ActionController::Parameters.new({ name: "John", age: 30 }) validations = { name: "string", age: "integer" } validator = HashValidator.validate(params, validations) expect(validator.valid?).to be true expect(validator.errors).to be_empty end it "should handle nested ActionController::Parameters" do nested_params = ActionController::Parameters.new({ theme: "dark" }) params = ActionController::Parameters.new({ name: "John", preferences: nested_params }) validations = { name: "string", preferences: { theme: "string" } } validator = HashValidator.validate(params, validations) expect(validator.valid?).to be true expect(validator.errors).to be_empty end it "should validate ActionController::Parameters with our new validators" do params = ActionController::Parameters.new({ name: "John", email: "john@example.com", website: "https://john.com", zip_code: "12345" }) validations = { name: "alpha", email: "email", website: "url", zip_code: "digits" } validator = HashValidator.validate(params, validations) expect(validator.valid?).to be true expect(validator.errors).to be_empty end it "should still work with regular hashes" do hash = { name: "John", age: 30 } validations = { name: "string", age: "integer" } validator = HashValidator.validate(hash, validations) expect(validator.valid?).to be true expect(validator.errors).to be_empty end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/base_spec.rb
spec/validators/base_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::Base do let(:name) { "my_validator" } it "allows a validator to be created with a valid name" do expect { HashValidator::Validator::Base.new(name) }.to_not raise_error end it "does not allow a validator to be created with an invalid name" do expect { HashValidator::Validator::Base.new(nil) }.to raise_error(StandardError, "Validator must be initialized with a valid name (length greater than zero)") expect { HashValidator::Validator::Base.new("") }.to raise_error(StandardError, "Validator must be initialized with a valid name (length greater than zero)") end describe "#validate" do let(:validator) { HashValidator::Validator::Base.new("test") } it "throws an exception as base validators must implement valid? or override validate" do expect { validator.validate("key", "value", {}, {}) }.to raise_error(StandardError, "Validator must implement either valid? or override validate method") end it "throws an exception when valid? method has invalid arity" do # Create a validator with a valid? method that accepts an invalid number of arguments (3) invalid_arity_validator = Class.new(HashValidator::Validator::Base) do def valid?(value, validations, extra_param) true end end.new("invalid_arity") expect { invalid_arity_validator.validate("key", "value", {}, {}) }.to raise_error(StandardError, "valid? method must accept either 1 argument (value) or 2 arguments (value, validations)") end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/lambda_spec.rb
spec/validators/lambda_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Functional validator" do describe "Accepting Lambdas in validations" do it "should accept a lambda" do validate({}, { foo: lambda { |arg| } }) end it "should accept a proc" do validate({}, { foo: Proc.new { |arg| } }) end end describe "Correct number of arguments for lambads in validations" do it "should accept a lambda with one argument" do expect { validate({}, { foo: lambda { |a| } }) }.to_not raise_error end it "should not accept a lambda with no arguments" do expect { validate({}, { foo: lambda { } }) }.to raise_error(HashValidator::Validator::LambdaValidator::InvalidArgumentCount) end it "should not accept a lambda with two arguments" do expect { validate({}, { foo: lambda { |a, b| } }) }.to raise_error(HashValidator::Validator::LambdaValidator::InvalidArgumentCount) end end describe "#validate" do let(:validations) { { number: lambda { |n| n.odd? } } } it "should validate true when the number is odd" do expect(validate({ number: 1 }, validations).valid?).to eq true end it "should validate false when the number is even" do expect(validate({ number: 2 }, validations).valid?).to eq false end end describe "Thrown exceptions from within the lambda" do let(:validations) { { number: lambda { |n| n.odd? } } } it "should validate false when an exception occurs within the lambda" do expect(validate({ number: "2" }, validations).valid?).to eq false end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/dynamic_func_validator_spec.rb
spec/validators/dynamic_func_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::DynamicFuncValidator do describe "Function-based validator" do let(:odd_func_validator) do HashValidator::Validator::DynamicFuncValidator.new( "odd_func", ->(n) { n.is_a?(Integer) && n.odd? }, "is not an odd integer" ) end let(:range_validator) do HashValidator::Validator::DynamicFuncValidator.new( "in_range", ->(n) { n.is_a?(Numeric) && n >= 18 && n <= 65 }, "must be between 18 and 65" ) end let(:custom_validator) do HashValidator::Validator::DynamicFuncValidator.new( "custom", proc { |v| v.to_s.length > 5 }, "must be longer than 5 characters" ) end let(:errors) { Hash.new } describe "#initialize" do it "requires a callable object" do expect { HashValidator::Validator::DynamicFuncValidator.new("test", "not_callable") }.to raise_error(ArgumentError, "Function must be callable (proc or lambda)") end it "accepts a lambda" do validator = HashValidator::Validator::DynamicFuncValidator.new( "test", ->(v) { true } ) expect(validator.func).to respond_to(:call) end it "accepts a proc" do validator = HashValidator::Validator::DynamicFuncValidator.new( "test", proc { |v| true } ) expect(validator.func).to respond_to(:call) end it "accepts a custom error message" do validator = HashValidator::Validator::DynamicFuncValidator.new( "test", ->(v) { true }, "custom error" ) expect(validator.error_message).to eq("custom error") end it "uses default error message when none provided" do validator = HashValidator::Validator::DynamicFuncValidator.new( "test", ->(v) { true } ) expect(validator.error_message).to eq("test required") end end describe "#should_validate?" do it "validates the correct name" do expect(odd_func_validator.should_validate?("odd_func")).to eq true end it "does not validate other names" do expect(odd_func_validator.should_validate?("even_func")).to eq false expect(odd_func_validator.should_validate?("string")).to eq false end end describe "#validate" do context "with odd number function" do it "validates odd integers correctly" do odd_func_validator.validate(:key, 1, {}, errors) expect(errors).to be_empty errors.clear odd_func_validator.validate(:key, 13, {}, errors) expect(errors).to be_empty errors.clear odd_func_validator.validate(:key, -7, {}, errors) expect(errors).to be_empty end it "rejects even integers" do odd_func_validator.validate(:key, 2, {}, errors) expect(errors).to eq({ key: "is not an odd integer" }) errors.clear odd_func_validator.validate(:key, 100, {}, errors) expect(errors).to eq({ key: "is not an odd integer" }) end it "rejects non-integers" do odd_func_validator.validate(:key, 1.5, {}, errors) expect(errors).to eq({ key: "is not an odd integer" }) errors.clear odd_func_validator.validate(:key, "1", {}, errors) expect(errors).to eq({ key: "is not an odd integer" }) end end context "with range validator" do it "validates numbers in range" do range_validator.validate(:key, 18, {}, errors) expect(errors).to be_empty errors.clear range_validator.validate(:key, 30, {}, errors) expect(errors).to be_empty errors.clear range_validator.validate(:key, 65, {}, errors) expect(errors).to be_empty errors.clear range_validator.validate(:key, 25.5, {}, errors) expect(errors).to be_empty end it "rejects numbers outside range" do range_validator.validate(:key, 17, {}, errors) expect(errors).to eq({ key: "must be between 18 and 65" }) errors.clear range_validator.validate(:key, 66, {}, errors) expect(errors).to eq({ key: "must be between 18 and 65" }) errors.clear range_validator.validate(:key, -5, {}, errors) expect(errors).to eq({ key: "must be between 18 and 65" }) end it "rejects non-numeric values" do range_validator.validate(:key, "twenty", {}, errors) expect(errors).to eq({ key: "must be between 18 and 65" }) end end context "with custom validator using proc" do it "validates strings longer than 5 chars" do custom_validator.validate(:key, "hello world", {}, errors) expect(errors).to be_empty errors.clear custom_validator.validate(:key, "testing", {}, errors) expect(errors).to be_empty end it "rejects strings 5 chars or shorter" do custom_validator.validate(:key, "hello", {}, errors) expect(errors).to eq({ key: "must be longer than 5 characters" }) errors.clear custom_validator.validate(:key, "hi", {}, errors) expect(errors).to eq({ key: "must be longer than 5 characters" }) end it "converts values to strings" do custom_validator.validate(:key, 123456, {}, errors) expect(errors).to be_empty errors.clear custom_validator.validate(:key, 12345, {}, errors) expect(errors).to eq({ key: "must be longer than 5 characters" }) end end context "with function that raises errors" do let(:error_func_validator) do HashValidator::Validator::DynamicFuncValidator.new( "error_func", ->(v) { raise "intentional error" }, "validation failed" ) end it "treats exceptions as validation failures" do error_func_validator.validate(:key, "any value", {}, errors) expect(errors).to eq({ key: "validation failed" }) end end end describe "Integration with HashValidator.add_validator" do before do HashValidator.add_validator("adult_age", func: ->(age) { age.is_a?(Integer) && age >= 18 }, error_message: "must be 18 or older") HashValidator.add_validator("palindrome", func: proc { |s| s.to_s == s.to_s.reverse }, error_message: "must be a palindrome") end after do HashValidator.remove_validator("adult_age") HashValidator.remove_validator("palindrome") end it "can register lambda-based validators" do validator = HashValidator.validate( { age: 25 }, { age: "adult_age" } ) expect(validator.valid?).to eq true expect(validator.errors).to be_empty end it "returns errors for invalid lambda validations" do validator = HashValidator.validate( { age: 16 }, { age: "adult_age" } ) expect(validator.valid?).to eq false expect(validator.errors).to eq({ age: "must be 18 or older" }) end it "can register proc-based validators" do validator = HashValidator.validate( { word: "racecar" }, { word: "palindrome" } ) expect(validator.valid?).to eq true expect(validator.errors).to be_empty end it "returns errors for invalid proc validations" do validator = HashValidator.validate( { word: "hello" }, { word: "palindrome" } ) expect(validator.valid?).to eq false expect(validator.errors).to eq({ word: "must be a palindrome" }) end end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/regexp_spec.rb
spec/validators/regexp_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Regular expression validator" do describe "Accepting RegExps in validations" do it "should accept a regexp" do validate({}, { foo: // }) end end describe "#validate" do let(:validations) { { string: /^foo$/ } } it "should validate true when the value is foo" do expect(validate({ string: "foo" }, validations).valid?).to eq true end it "should validate false when the value is not foo" do expect(validate({ string: "bar" }, validations).valid?).to eq false expect(validate({ string: " foo" }, validations).valid?).to eq false expect(validate({ string: "foo " }, validations).valid?).to eq false expect(validate({ string: nil }, validations).valid?).to eq false expect(validate({ string: 0 }, validations).valid?).to eq false expect(validate({ string: true }, validations).valid?).to eq false end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/boolean_spec.rb
spec/validators/boolean_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::Base do let(:validator) { HashValidator::Validator::BooleanValidator.new } let(:errors) { Hash.new } describe "#should_validate?" do it 'should validate the name "boolean"' do expect(validator.should_validate?("boolean")).to eq true end it "should not validate other names" do expect(validator.should_validate?("string")).to eq false expect(validator.should_validate?("array")).to eq false expect(validator.should_validate?(nil)).to eq false end end describe "#validate" do it "should validate a true boolean with true" do validator.validate(:key, true, {}, errors) expect(errors).to be_empty end it "should validate a false boolean with true" do validator.validate(:key, false, {}, errors) expect(errors).to be_empty end it "should validate a nil with false" do validator.validate(:key, nil, {}, errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "boolean required" }) end it "should validate a number with false" do validator.validate(:key, 123, {}, errors) expect(errors).not_to be_empty expect(errors).to eq({ key: "boolean required" }) end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/alphanumeric_validator_spec.rb
spec/validators/alphanumeric_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::AlphanumericValidator do let(:validator) { HashValidator::Validator::AlphanumericValidator.new } context "valid alphanumeric strings" do it "validates letters only" do errors = {} validator.validate("key", "abc", {}, errors) expect(errors).to be_empty end it "validates numbers only" do errors = {} validator.validate("key", "123", {}, errors) expect(errors).to be_empty end it "validates mixed letters and numbers" do errors = {} validator.validate("key", "abc123", {}, errors) expect(errors).to be_empty end it "validates uppercase letters" do errors = {} validator.validate("key", "ABC", {}, errors) expect(errors).to be_empty end it "validates mixed case letters" do errors = {} validator.validate("key", "AbC123", {}, errors) expect(errors).to be_empty end it "validates single character" do errors = {} validator.validate("key", "a", {}, errors) expect(errors).to be_empty end it "validates single digit" do errors = {} validator.validate("key", "1", {}, errors) expect(errors).to be_empty end end context "invalid alphanumeric strings" do it "rejects non-string values" do errors = {} validator.validate("key", 123, {}, errors) expect(errors["key"]).to eq("must contain only letters and numbers") end it "rejects nil values" do errors = {} validator.validate("key", nil, {}, errors) expect(errors["key"]).to eq("must contain only letters and numbers") end it "rejects strings with spaces" do errors = {} validator.validate("key", "abc 123", {}, errors) expect(errors["key"]).to eq("must contain only letters and numbers") end it "rejects strings with special characters" do errors = {} validator.validate("key", "abc!123", {}, errors) expect(errors["key"]).to eq("must contain only letters and numbers") end it "rejects strings with hyphens" do errors = {} validator.validate("key", "abc-123", {}, errors) expect(errors["key"]).to eq("must contain only letters and numbers") end it "rejects strings with underscores" do errors = {} validator.validate("key", "abc_123", {}, errors) expect(errors["key"]).to eq("must contain only letters and numbers") end it "rejects empty strings" do errors = {} validator.validate("key", "", {}, errors) expect(errors["key"]).to eq("must contain only letters and numbers") end it "rejects strings with periods" do errors = {} validator.validate("key", "abc.123", {}, errors) expect(errors["key"]).to eq("must contain only letters and numbers") end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/ipv4_validator_spec.rb
spec/validators/ipv4_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::Ipv4Validator do let(:validator) { HashValidator::Validator::Ipv4Validator.new } context "valid IPv4 addresses" do it "validates standard IPv4 addresses" do errors = {} validator.validate("key", "192.168.1.1", {}, errors) expect(errors).to be_empty end it "validates localhost" do errors = {} validator.validate("key", "127.0.0.1", {}, errors) expect(errors).to be_empty end it "validates zero address" do errors = {} validator.validate("key", "0.0.0.0", {}, errors) expect(errors).to be_empty end it "validates broadcast address" do errors = {} validator.validate("key", "255.255.255.255", {}, errors) expect(errors).to be_empty end it "validates private network addresses" do errors = {} validator.validate("key", "10.0.0.1", {}, errors) expect(errors).to be_empty end it "validates Class B private addresses" do errors = {} validator.validate("key", "172.16.0.1", {}, errors) expect(errors).to be_empty end end context "invalid IPv4 addresses" do it "rejects non-string values" do errors = {} validator.validate("key", 123, {}, errors) expect(errors["key"]).to eq("is not a valid IPv4 address") end it "rejects nil values" do errors = {} validator.validate("key", nil, {}, errors) expect(errors["key"]).to eq("is not a valid IPv4 address") end it "rejects octets over 255" do errors = {} validator.validate("key", "256.1.1.1", {}, errors) expect(errors["key"]).to eq("is not a valid IPv4 address") end it "rejects too few octets" do errors = {} validator.validate("key", "192.168.1", {}, errors) expect(errors["key"]).to eq("is not a valid IPv4 address") end it "rejects too many octets" do errors = {} validator.validate("key", "192.168.1.1.1", {}, errors) expect(errors["key"]).to eq("is not a valid IPv4 address") end it "rejects IPv6 addresses" do errors = {} validator.validate("key", "2001:db8::1", {}, errors) expect(errors["key"]).to eq("is not a valid IPv4 address") end it "rejects malformed addresses" do errors = {} validator.validate("key", "192.168.1.", {}, errors) expect(errors["key"]).to eq("is not a valid IPv4 address") end it "rejects empty strings" do errors = {} validator.validate("key", "", {}, errors) expect(errors["key"]).to eq("is not a valid IPv4 address") end it "rejects non-numeric octets" do errors = {} validator.validate("key", "192.168.a.1", {}, errors) expect(errors["key"]).to eq("is not a valid IPv4 address") end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/dynamic_pattern_validator_spec.rb
spec/validators/dynamic_pattern_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::DynamicPatternValidator do describe "Pattern-based validator" do let(:odd_pattern_validator) do HashValidator::Validator::DynamicPatternValidator.new( "odd_pattern", /\A\d*[13579]\z/, "is not an odd number" ) end let(:postal_code_validator) do HashValidator::Validator::DynamicPatternValidator.new( "us_postal", /\A\d{5}(-\d{4})?\z/, "is not a valid US postal code" ) end let(:errors) { Hash.new } describe "#initialize" do it "requires a valid regular expression" do expect { HashValidator::Validator::DynamicPatternValidator.new("test", "not_a_regex") }.to raise_error(ArgumentError, "Pattern must be a regular expression") end it "accepts a custom error message" do validator = HashValidator::Validator::DynamicPatternValidator.new( "test", /test/, "custom error" ) expect(validator.error_message).to eq("custom error") end it "uses default error message when none provided" do validator = HashValidator::Validator::DynamicPatternValidator.new("test", /test/) expect(validator.error_message).to eq("test required") end end describe "#should_validate?" do it "validates the correct name" do expect(odd_pattern_validator.should_validate?("odd_pattern")).to eq true end it "does not validate other names" do expect(odd_pattern_validator.should_validate?("even_pattern")).to eq false expect(odd_pattern_validator.should_validate?("string")).to eq false end end describe "#validate" do context "with odd number pattern" do it "validates odd numbers correctly" do odd_pattern_validator.validate(:key, "1", {}, errors) expect(errors).to be_empty errors.clear odd_pattern_validator.validate(:key, "13", {}, errors) expect(errors).to be_empty errors.clear odd_pattern_validator.validate(:key, "999", {}, errors) expect(errors).to be_empty end it "rejects even numbers" do odd_pattern_validator.validate(:key, "2", {}, errors) expect(errors).to eq({ key: "is not an odd number" }) errors.clear odd_pattern_validator.validate(:key, "100", {}, errors) expect(errors).to eq({ key: "is not an odd number" }) end it "rejects non-numeric strings" do odd_pattern_validator.validate(:key, "abc", {}, errors) expect(errors).to eq({ key: "is not an odd number" }) end it "converts non-string values to strings" do odd_pattern_validator.validate(:key, 13, {}, errors) expect(errors).to be_empty errors.clear odd_pattern_validator.validate(:key, 14, {}, errors) expect(errors).to eq({ key: "is not an odd number" }) end end context "with postal code pattern" do it "validates correct postal codes" do postal_code_validator.validate(:key, "12345", {}, errors) expect(errors).to be_empty errors.clear postal_code_validator.validate(:key, "12345-6789", {}, errors) expect(errors).to be_empty end it "rejects invalid postal codes" do postal_code_validator.validate(:key, "1234", {}, errors) expect(errors).to eq({ key: "is not a valid US postal code" }) errors.clear postal_code_validator.validate(:key, "12345-678", {}, errors) expect(errors).to eq({ key: "is not a valid US postal code" }) errors.clear postal_code_validator.validate(:key, "ABCDE", {}, errors) expect(errors).to eq({ key: "is not a valid US postal code" }) end end end describe "Integration with HashValidator.add_validator" do before do HashValidator.add_validator("phone_number", pattern: /\A\d{3}-\d{3}-\d{4}\z/, error_message: "is not a valid phone number") end after do HashValidator.remove_validator("phone_number") end it "can be registered and used via add_validator" do validator = HashValidator.validate( { phone: "555-123-4567" }, { phone: "phone_number" } ) expect(validator.valid?).to eq true expect(validator.errors).to be_empty end it "returns errors for invalid values" do validator = HashValidator.validate( { phone: "5551234567" }, { phone: "phone_number" } ) expect(validator.valid?).to eq false expect(validator.errors).to eq({ phone: "is not a valid phone number" }) end end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/json_validator_spec.rb
spec/validators/json_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::JsonValidator do let(:validator) { HashValidator::Validator::JsonValidator.new } context "valid JSON" do it "validates simple JSON objects" do errors = {} validator.validate("key", '{"name": "test"}', {}, errors) expect(errors).to be_empty end it "validates JSON arrays" do errors = {} validator.validate("key", "[1, 2, 3]", {}, errors) expect(errors).to be_empty end it "validates JSON strings" do errors = {} validator.validate("key", '"hello world"', {}, errors) expect(errors).to be_empty end it "validates JSON numbers" do errors = {} validator.validate("key", "42", {}, errors) expect(errors).to be_empty end it "validates JSON booleans" do errors = {} validator.validate("key", "true", {}, errors) expect(errors).to be_empty end it "validates JSON null" do errors = {} validator.validate("key", "null", {}, errors) expect(errors).to be_empty end it "validates complex nested JSON" do errors = {} json_string = '{"users": [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]}' validator.validate("key", json_string, {}, errors) expect(errors).to be_empty end end context "invalid JSON" do it "rejects non-string values" do errors = {} validator.validate("key", 123, {}, errors) expect(errors["key"]).to eq("is not valid JSON") end it "rejects nil values" do errors = {} validator.validate("key", nil, {}, errors) expect(errors["key"]).to eq("is not valid JSON") end it "rejects malformed JSON" do errors = {} validator.validate("key", '{"name": "test"', {}, errors) expect(errors["key"]).to eq("is not valid JSON") end it "rejects invalid JSON syntax" do errors = {} validator.validate("key", '{name: "test"}', {}, errors) expect(errors["key"]).to eq("is not valid JSON") end it "rejects empty strings" do errors = {} validator.validate("key", "", {}, errors) expect(errors["key"]).to eq("is not valid JSON") end it "rejects plain text" do errors = {} validator.validate("key", "hello world", {}, errors) expect(errors["key"]).to eq("is not valid JSON") end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/spec/validators/url_validator_spec.rb
spec/validators/url_validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe HashValidator::Validator::UrlValidator do let(:validator) { HashValidator::Validator::UrlValidator.new } context "valid URLs" do it "validates http URLs" do errors = {} validator.validate("key", "http://example.com", {}, errors) expect(errors).to be_empty end it "validates https URLs" do errors = {} validator.validate("key", "https://example.com", {}, errors) expect(errors).to be_empty end it "validates ftp URLs" do errors = {} validator.validate("key", "ftp://ftp.example.com", {}, errors) expect(errors).to be_empty end it "validates URLs with paths" do errors = {} validator.validate("key", "https://example.com/path/to/resource", {}, errors) expect(errors).to be_empty end it "validates URLs with query parameters" do errors = {} validator.validate("key", "https://example.com/search?q=test&page=1", {}, errors) expect(errors).to be_empty end end context "invalid URLs" do it "rejects non-string values" do errors = {} validator.validate("key", 123, {}, errors) expect(errors["key"]).to eq("is not a valid URL") end it "rejects nil values" do errors = {} validator.validate("key", nil, {}, errors) expect(errors["key"]).to eq("is not a valid URL") end it "rejects malformed URLs" do errors = {} validator.validate("key", "not a url", {}, errors) expect(errors["key"]).to eq("is not a valid URL") end it "rejects URLs without schemes" do errors = {} validator.validate("key", "example.com", {}, errors) expect(errors["key"]).to eq("is not a valid URL") end it "rejects unsupported schemes" do errors = {} validator.validate("key", "mailto:test@example.com", {}, errors) expect(errors["key"]).to eq("is not a valid URL") end it "rejects empty strings" do errors = {} validator.validate("key", "", {}, errors) expect(errors["key"]).to eq("is not a valid URL") end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator.rb
lib/hash_validator.rb
# frozen_string_literal: true module HashValidator def self.validate(*args) Base.validate(*args) end def self.optional(validation) Validations::Optional.new(validation) end def self.many(validation) Validations::Many.new(validation) end def self.multiple(*validations) Validations::Multiple.new(validations) end end require "hash_validator/base" require "hash_validator/version" require "hash_validator/validators" require "hash_validator/validations" require "hash_validator/configuration"
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/version.rb
lib/hash_validator/version.rb
# frozen_string_literal: true module HashValidator VERSION = "2.0.1" end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validations.rb
lib/hash_validator/validations.rb
# frozen_string_literal: true module HashValidator module Validations end end # Load validators require "hash_validator/validations/optional" require "hash_validator/validations/many" require "hash_validator/validations/multiple"
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/base.rb
lib/hash_validator/base.rb
# frozen_string_literal: true class HashValidator::Base attr_accessor :hash, :validations, :errors def initialize(hash, validations) self.errors = {} self.hash = hash self.validations = validations validate end def valid? errors.empty? end def self.validate(hash, validations, strict = false) @strict = strict new(hash, validations) end def self.strict? @strict end private def validate HashValidator.validator_for(hash).validate(:base, self.hash, self.validations, self.errors) self.errors = errors[:base] end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/configuration.rb
lib/hash_validator/configuration.rb
# frozen_string_literal: true module HashValidator class Configuration def add_validator(*args) HashValidator.add_validator(*args) end def remove_validator(name) HashValidator.remove_validator(name) end end def self.configure config = Configuration.new yield(config) if block_given? end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators.rb
lib/hash_validator/validators.rb
# frozen_string_literal: true module HashValidator @@validators = [] def self.remove_validator(name) name = name.to_s @@validators.reject! { |v| v.name == name } end def self.add_validator(*args) validator = case args.length when 1 # Instance-based validator (existing behavior) validator_instance = args[0] unless validator_instance.is_a?(HashValidator::Validator::Base) raise StandardError.new("validators need to inherit from HashValidator::Validator::Base") end validator_instance when 2 # Dynamic validator with options name = args[0] options = args[1] if options.is_a?(Hash) if options[:pattern] # Pattern-based validator HashValidator::Validator::DynamicPatternValidator.new(name, options[:pattern], options[:error_message]) elsif options[:func] # Function-based validator HashValidator::Validator::DynamicFuncValidator.new(name, options[:func], options[:error_message]) else raise ArgumentError, "Options hash must contain either :pattern or :func key" end else raise ArgumentError, "Second argument must be an options hash with :pattern or :func key" end else raise ArgumentError, "add_validator expects 1 argument (validator instance) or 2 arguments (name, options)" end if @@validators.detect { |v| v.name == validator.name } raise StandardError.new("validators need to have unique names") end @@validators << validator end def self.validator_for(rhs) @@validators.detect { |v| v.should_validate?(rhs) } || raise(StandardError.new("Could not find valid validator for: #{rhs}")) end module Validator end end # Load validators require "hash_validator/validators/base" require "hash_validator/validators/dynamic_pattern_validator" require "hash_validator/validators/dynamic_func_validator" require "hash_validator/validators/simple_validator" require "hash_validator/validators/class_validator" require "hash_validator/validators/hash_validator" require "hash_validator/validators/presence_validator" require "hash_validator/validators/simple_type_validators" require "hash_validator/validators/boolean_validator" require "hash_validator/validators/email_validator" require "hash_validator/validators/enumerable_validator" require "hash_validator/validators/regex_validator" require "hash_validator/validators/lambda_validator" require "hash_validator/validators/optional_validator" require "hash_validator/validators/many_validator" require "hash_validator/validators/multiple_validator" require "hash_validator/validators/array_validator" require "hash_validator/validators/url_validator" require "hash_validator/validators/json_validator" require "hash_validator/validators/hex_color_validator" require "hash_validator/validators/alphanumeric_validator" require "hash_validator/validators/alpha_validator" require "hash_validator/validators/digits_validator" require "hash_validator/validators/ipv4_validator" require "hash_validator/validators/ipv6_validator" require "hash_validator/validators/ip_validator"
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/url_validator.rb
lib/hash_validator/validators/url_validator.rb
# frozen_string_literal: true require "uri" class HashValidator::Validator::UrlValidator < HashValidator::Validator::Base def initialize super("url") # The name of the validator end def error_message "is not a valid URL" end def valid?(value) return false unless value.is_a?(String) uri = URI.parse(value) %w[http https ftp].include?(uri.scheme) rescue URI::InvalidURIError false end end HashValidator.add_validator(HashValidator::Validator::UrlValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/multiple_validator.rb
lib/hash_validator/validators/multiple_validator.rb
# frozen_string_literal: true module HashValidator module Validator class MultipleValidator < Base def initialize super("_multiple") # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator) end def should_validate?(validation) validation.is_a?(Validations::Multiple) end def validate(key, value, validations, errors) multiple_errors = [] validations.validations.each do |validation| validation_error = {} ::HashValidator.validator_for(validation).validate(key, value, validation, validation_error) multiple_errors << validation_error[key] if validation_error[key] end errors[key] = multiple_errors.join(", ") if multiple_errors.any? end end end end HashValidator.add_validator(HashValidator::Validator::MultipleValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/regex_validator.rb
lib/hash_validator/validators/regex_validator.rb
# frozen_string_literal: true class HashValidator::Validator::RegexpValidator < HashValidator::Validator::Base def initialize super("_regex") # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator) end def should_validate?(rhs) rhs.is_a?(Regexp) end def error_message "does not match regular expression" end def valid?(value, regexp) regexp.match(value.to_s) end end HashValidator.add_validator(HashValidator::Validator::RegexpValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/alphanumeric_validator.rb
lib/hash_validator/validators/alphanumeric_validator.rb
# frozen_string_literal: true class HashValidator::Validator::AlphanumericValidator < HashValidator::Validator::Base def initialize super("alphanumeric") # The name of the validator end def error_message "must contain only letters and numbers" end def valid?(value) value.is_a?(String) && /\A[a-zA-Z0-9]+\z/.match?(value) end end HashValidator.add_validator(HashValidator::Validator::AlphanumericValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/ipv4_validator.rb
lib/hash_validator/validators/ipv4_validator.rb
# frozen_string_literal: true class HashValidator::Validator::Ipv4Validator < HashValidator::Validator::Base def initialize super("ipv4") # The name of the validator end def error_message "is not a valid IPv4 address" end def valid?(value) return false unless value.is_a?(String) # IPv4 regex: 4 octets, each 0-255 ipv4_regex = /\A(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\z/ value.match?(ipv4_regex) end end HashValidator.add_validator(HashValidator::Validator::Ipv4Validator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/hash_validator.rb
lib/hash_validator/validators/hash_validator.rb
# frozen_string_literal: true class HashValidator::Validator::HashValidator < HashValidator::Validator::Base def initialize super("hash") end def should_validate?(rhs) rhs.is_a?(Hash) || (defined?(ActionController::Parameters) && rhs.is_a?(ActionController::Parameters)) end def validate(key, value, validations, errors) # Convert ActionController::Parameters to Hash if needed if !value.is_a?(Hash) && defined?(ActionController::Parameters) && value.is_a?(ActionController::Parameters) value = value.to_unsafe_h end # Validate hash unless value.is_a?(Hash) errors[key] = error_message return end # Hashes can contain sub-elements, attempt to validator those errors = (errors[key] = {}) validations.each do |v_key, v_value| HashValidator.validator_for(v_value).validate(v_key, value[v_key], v_value, errors) end if HashValidator::Base.strict? value.keys.each do |k| errors[k] = "key not expected" unless validations[k] end end # Cleanup errors (remove any empty nested errors) errors.delete_if { |_, v| v.empty? } end end HashValidator.add_validator(HashValidator::Validator::HashValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/json_validator.rb
lib/hash_validator/validators/json_validator.rb
# frozen_string_literal: true require "json" class HashValidator::Validator::JsonValidator < HashValidator::Validator::Base def initialize super("json") # The name of the validator end def error_message "is not valid JSON" end def valid?(value) return false unless value.is_a?(String) JSON.parse(value) true rescue JSON::ParserError false end end HashValidator.add_validator(HashValidator::Validator::JsonValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/class_validator.rb
lib/hash_validator/validators/class_validator.rb
# frozen_string_literal: true class HashValidator::Validator::ClassValidator < HashValidator::Validator::Base def initialize super("_class") # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator) end def should_validate?(rhs) rhs.is_a?(Class) end def validate(key, value, klass, errors) unless value.is_a?(klass) errors[key] = "#{klass} required" end end end HashValidator.add_validator(HashValidator::Validator::ClassValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/many_validator.rb
lib/hash_validator/validators/many_validator.rb
# frozen_string_literal: true module HashValidator module Validator class ManyValidator < Base def initialize super("_many") # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator) end def should_validate?(validation) validation.is_a?(Validations::Many) end def error_message "enumerable required" end def validate(key, value, validations, errors) unless value.is_a?(Enumerable) errors[key] = error_message return end element_errors = Array.new value.each_with_index do |element, i| ::HashValidator.validator_for(validations.validation).validate(i, element, validations.validation, element_errors) end element_errors.each_with_index do |e, i| if e.respond_to?(:empty?) && e.empty? element_errors[i] = nil end end errors[key] = element_errors unless element_errors.all?(&:nil?) end end end end HashValidator.add_validator(HashValidator::Validator::ManyValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/array_validator.rb
lib/hash_validator/validators/array_validator.rb
# frozen_string_literal: true class HashValidator::Validator::ArrayValidator < HashValidator::Validator::Base def initialize super("__array__") # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator) end def should_validate?(rhs) return false unless rhs.is_a?(Array) return false unless rhs.size > 0 return false unless rhs[0] == :array true end def validate(key, value, specification, errors) # Validate specification format if specification[0] != :array errors[key] = "Wrong array specification. The #{:array} is expected as first item." elsif specification.size > 2 errors[key] = "Wrong size of array specification. Allowed is one or two items." elsif !value.is_a?(Array) errors[key] = "#{Array} required" elsif specification.size >= 2 && !specification[1].nil? validate_array_specification(key, value, specification[1], errors) end end private def validate_array_specification(key, value, array_spec, errors) # Convert numeric specification to hash format array_spec = { size: array_spec } if array_spec.is_a?(Numeric) unless array_spec.is_a?(Hash) errors[key] = "Second item of array specification must be #{Hash} or #{Numeric}." return end return if array_spec.empty? validate_size_specification(key, value, array_spec, errors) if errors.empty? validate_allowed_keys(key, array_spec, errors) if errors.empty? end def validate_size_specification(key, value, array_spec, errors) size_spec = array_spec[:size] size_spec_present = case size_spec when String !size_spec.strip.empty? when NilClass false when Numeric true when Array, Hash !size_spec.empty? else !!size_spec end if size_spec_present && value.size != size_spec errors[key] = "The required size of array is #{size_spec} but is #{value.size}." end end def validate_allowed_keys(key, array_spec, errors) allowed_keys = [:size] wrong_keys = array_spec.keys - allowed_keys if wrong_keys.any? errors[key] = "Not supported specification for array: #{wrong_keys.sort.join(", ")}." end end end HashValidator.add_validator(HashValidator::Validator::ArrayValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/dynamic_func_validator.rb
lib/hash_validator/validators/dynamic_func_validator.rb
# frozen_string_literal: true class HashValidator::Validator::DynamicFuncValidator < HashValidator::Validator::Base attr_accessor :func, :custom_error_message def initialize(name, func, error_message = nil) super(name) unless func.respond_to?(:call) raise ArgumentError, "Function must be callable (proc or lambda)" end @func = func @custom_error_message = error_message end def error_message @custom_error_message || super end def valid?(value) !!@func.call(value) rescue false end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/alpha_validator.rb
lib/hash_validator/validators/alpha_validator.rb
# frozen_string_literal: true class HashValidator::Validator::AlphaValidator < HashValidator::Validator::Base def initialize super("alpha") # The name of the validator end def error_message "must contain only letters" end def valid?(value) value.is_a?(String) && /\A[a-zA-Z]+\z/.match?(value) end end HashValidator.add_validator(HashValidator::Validator::AlphaValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/presence_validator.rb
lib/hash_validator/validators/presence_validator.rb
# frozen_string_literal: true class HashValidator::Validator::PresenceValidator < HashValidator::Validator::Base def initialize super("required") end def error_message "is required" end def valid?(value) !value.nil? end end HashValidator.add_validator(HashValidator::Validator::PresenceValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/base.rb
lib/hash_validator/validators/base.rb
# frozen_string_literal: true class HashValidator::Validator::Base attr_accessor :name def initialize(name) self.name = name.to_s unless self.name.size > 0 raise StandardError.new("Validator must be initialized with a valid name (length greater than zero)") end end def should_validate?(name) self.name == name.to_s end def error_message "#{self.name} required" end def validate(key, value, validations, errors) # If the subclass implements valid?, use that for simple boolean validation if self.class.instance_methods(false).include?(:valid?) # Check the arity of the valid? method to determine how many arguments to pass valid_result = case method(:valid?).arity when 1 valid?(value) when 2 valid?(value, validations) else raise StandardError.new("valid? method must accept either 1 argument (value) or 2 arguments (value, validations)") end unless valid_result errors[key] = error_message end else # Otherwise, subclass must override validate raise StandardError.new("Validator must implement either valid? or override validate method") end end # Subclasses can optionally implement this for simple boolean validation # Return true if valid, false if invalid # Either: # def valid?(value) # For simple validations # def valid?(value, validations) # When validation context is needed # end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/email_validator.rb
lib/hash_validator/validators/email_validator.rb
# frozen_string_literal: true class HashValidator::Validator::EmailValidator < HashValidator::Validator::Base def initialize super("email") # The name of the validator end def error_message "is not a valid email" end def valid?(value) value.is_a?(String) && value.include?("@") end end HashValidator.add_validator(HashValidator::Validator::EmailValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/lambda_validator.rb
lib/hash_validator/validators/lambda_validator.rb
# frozen_string_literal: true class HashValidator::Validator::LambdaValidator < HashValidator::Validator::Base def initialize super("_lambda") # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator) end def should_validate?(rhs) if rhs.is_a?(Proc) if rhs.arity == 1 true else raise HashValidator::Validator::LambdaValidator::InvalidArgumentCount.new("Lambda validator should only accept one argument, supplied lambda accepts #{rhs.arity}.") end else false end end def error_message "is not valid" end def valid?(value, lambda) lambda.call(value) rescue false end end class HashValidator::Validator::LambdaValidator::InvalidArgumentCount < StandardError end HashValidator.add_validator(HashValidator::Validator::LambdaValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/hex_color_validator.rb
lib/hash_validator/validators/hex_color_validator.rb
# frozen_string_literal: true class HashValidator::Validator::HexColorValidator < HashValidator::Validator::Base def initialize super("hex_color") # The name of the validator end def error_message "is not a valid hex color" end def valid?(value) value.is_a?(String) && /\A#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})\z/.match?(value) end end HashValidator.add_validator(HashValidator::Validator::HexColorValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/digits_validator.rb
lib/hash_validator/validators/digits_validator.rb
# frozen_string_literal: true class HashValidator::Validator::DigitsValidator < HashValidator::Validator::Base def initialize super("digits") # The name of the validator end def error_message "must contain only digits" end def valid?(value) value.is_a?(String) && /\A\d+\z/.match?(value) end end HashValidator.add_validator(HashValidator::Validator::DigitsValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/simple_validator.rb
lib/hash_validator/validators/simple_validator.rb
# frozen_string_literal: true class HashValidator::Validator::SimpleValidator < HashValidator::Validator::Base attr_accessor :lambda def initialize(name, lambda) # lambda must accept one argument (the value) if lambda.arity != 1 raise StandardError.new("lambda should take only one argument - passed lambda takes #{lambda.arity}") end super(name) self.lambda = lambda end def valid?(value) lambda.call(value) end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/simple_type_validators.rb
lib/hash_validator/validators/simple_type_validators.rb
# frozen_string_literal: true [ Array, Complex, Enumerable, Float, Integer, Numeric, Range, Rational, Regexp, String, Symbol, Time ].each do |type| name = type.to_s.gsub(/(.)([A-Z])/, '\1_\2').downcase # ActiveSupport/Inflector#underscore behaviour HashValidator.add_validator(HashValidator::Validator::SimpleValidator.new(name, lambda { |v| v.is_a?(type) })) end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/ip_validator.rb
lib/hash_validator/validators/ip_validator.rb
# frozen_string_literal: true require "ipaddr" class HashValidator::Validator::IpValidator < HashValidator::Validator::Base def initialize super("ip") # The name of the validator end def error_message "is not a valid IP address" end def valid?(value) return false unless value.is_a?(String) # Use IPAddr to validate both IPv4 and IPv6 addresses IPAddr.new(value) true rescue IPAddr::Error, IPAddr::InvalidAddressError false end end HashValidator.add_validator(HashValidator::Validator::IpValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/optional_validator.rb
lib/hash_validator/validators/optional_validator.rb
# frozen_string_literal: true module HashValidator module Validator class OptionalValidator < Base def initialize super("_optional") # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator) end def should_validate?(validation) validation.is_a?(Validations::Optional) end def validate(key, value, validations, errors) unless value.nil? ::HashValidator.validator_for(validations.validation).validate(key, value, validations.validation, errors) errors.delete(key) if errors[key].respond_to?(:empty?) && errors[key].empty? end end end end end HashValidator.add_validator(HashValidator::Validator::OptionalValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/dynamic_pattern_validator.rb
lib/hash_validator/validators/dynamic_pattern_validator.rb
# frozen_string_literal: true class HashValidator::Validator::DynamicPatternValidator < HashValidator::Validator::Base attr_accessor :pattern, :custom_error_message def initialize(name, pattern, error_message = nil) super(name) unless pattern.is_a?(Regexp) raise ArgumentError, "Pattern must be a regular expression" end @pattern = pattern @custom_error_message = error_message end def error_message @custom_error_message || super end def valid?(value) return false unless value.respond_to?(:to_s) @pattern.match?(value.to_s) end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/enumerable_validator.rb
lib/hash_validator/validators/enumerable_validator.rb
# frozen_string_literal: true class HashValidator::Validator::EnumerableValidator < HashValidator::Validator::Base def initialize super("_enumerable") # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator) end def should_validate?(rhs) rhs.is_a?(Enumerable) end def error_message "value from list required" end def valid?(value, validations) validations.include?(value) end end HashValidator.add_validator(HashValidator::Validator::EnumerableValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/ipv6_validator.rb
lib/hash_validator/validators/ipv6_validator.rb
# frozen_string_literal: true require "ipaddr" class HashValidator::Validator::Ipv6Validator < HashValidator::Validator::Base def initialize super("ipv6") # The name of the validator end def error_message "is not a valid IPv6 address" end def valid?(value) return false unless value.is_a?(String) # Use IPAddr to validate IPv6 addresses (handles standard and compressed notation) addr = IPAddr.new(value) addr.ipv6? rescue IPAddr::Error, IPAddr::InvalidAddressError false end end HashValidator.add_validator(HashValidator::Validator::Ipv6Validator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validators/boolean_validator.rb
lib/hash_validator/validators/boolean_validator.rb
# frozen_string_literal: true class HashValidator::Validator::BooleanValidator < HashValidator::Validator::Base def initialize super("boolean") # The name of the validator end def valid?(value) [TrueClass, FalseClass].include?(value.class) end end HashValidator.add_validator(HashValidator::Validator::BooleanValidator.new)
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validations/optional.rb
lib/hash_validator/validations/optional.rb
# frozen_string_literal: true module HashValidator::Validations class Optional attr_reader :validation def initialize(validation) @validation = validation end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validations/many.rb
lib/hash_validator/validations/many.rb
# frozen_string_literal: true module HashValidator::Validations class Many attr_reader :validation def initialize(validation) @validation = validation end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
jamesbrooks/hash_validator
https://github.com/jamesbrooks/hash_validator/blob/05b09c196cb6ef3af5a36030ed70450b9d9baef0/lib/hash_validator/validations/multiple.rb
lib/hash_validator/validations/multiple.rb
# frozen_string_literal: true module HashValidator::Validations class Multiple attr_reader :validations def initialize(validations) @validations = validations end end end
ruby
MIT
05b09c196cb6ef3af5a36030ed70450b9d9baef0
2026-01-04T17:49:06.790742Z
false
postmodern/nokogiri-diff
https://github.com/postmodern/nokogiri-diff/blob/ea873edceb4e42fcdfc5a729ba899dff6ee68d80/spec/diff_spec.rb
spec/diff_spec.rb
require 'spec_helper' require 'nokogiri/diff' describe "nokogiri/diff" do let(:contents) { '<div><p>one</p></div>' } let(:doc) { Nokogiri::XML(contents) } let(:added_text) { Nokogiri::XML('<div><p>one</p>two</div>') } let(:added_element) { Nokogiri::XML('<div><p>one</p><p>two</p></div>') } let(:added_attr) { Nokogiri::XML('<div><p id="1">one</p></div>') } let(:added_attrs) { Nokogiri::XML('<div><p id="1" class="2">one</p></div>') } let(:changed_text) { Nokogiri::XML('<div><p>two</p></div>') } let(:changed_element) { Nokogiri::XML('<div><span>one</span></div>') } let(:changed_attr_name) { Nokogiri::XML('<div><p i="1">one</p></div>') } let(:changed_attr_value) { Nokogiri::XML('<div><p id="2">one</p></div>') } let(:changed_attr_order) { Nokogiri::XML('<div><p class="2" id="1">one</p></div>') } let(:removed_text) { Nokogiri::XML('<div><p></p>two</div>') } let(:removed_element) { Nokogiri::XML('<div></div>') } let(:removed_attr) { Nokogiri::XML('<div><p>one</p></div>') } it "should add #diff to Nokogiri::XML::Docuemnt" do expect(doc).to respond_to(:diff) end it "should add #diff to Nokogiri::XML::Element" do expect(added_element.at('div')).to respond_to(:diff) end it "should add #diff to Nokogiri::XML::Text" do expect(added_text.at('p/text()')).to respond_to(:diff) end it "should add #diff to Nokogiri::XML::Attr" do expect(added_attr.at('p/@id')).to respond_to(:diff) end it "should not compare the Document objects" do change = doc.diff(doc).first expect(change[0]).to eq(' ') expect(change[1]).to eq(doc.root) end it "should determine when two different documents are identical" do expect(doc.diff(Nokogiri::XML(contents)).all? { |change,node| change == ' ' }).to eq(true) end it "should search down within Nokogiri::XML::Document objects" do expect(doc.diff(changed_text).any? { |change,node| change != ' ' }).to eq(true) end it "should determine when text nodes are added" do changes = doc.at('div').diff(added_text.at('div')).to_a expect(changes.length).to eq(4) expect(changes[0][0]).to eq(' ') expect(changes[0][1]).to eq(doc.at('div')) expect(changes[1][0]).to eq(' ') expect(changes[1][1]).to eq(doc.at('//p')) expect(changes[2][0]).to eq('+') expect(changes[2][1]).to eq(added_text.at('//div/text()')) expect(changes[3][0]).to eq(' ') expect(changes[3][1]).to eq(doc.at('//p/text()')) end it "should determine when elements are added" do changes = doc.at('div').diff(added_element.at('div')).to_a expect(changes.length).to eq(5) expect(changes[0][0]).to eq(' ') expect(changes[0][1]).to eq(doc.at('div')) expect(changes[1][0]).to eq('+') expect(changes[1][1]).to eq(added_element.at('//p[1]')) expect(changes[2][0]).to eq(' ') expect(changes[2][1]).to eq(doc.at('//p')) expect(changes[3][0]).to eq('-') expect(changes[3][1]).to eq(doc.at('//p/text()')) expect(changes[4][0]).to eq('+') expect(changes[4][1]).to eq(added_element.at('//p[2]/text()')) end it "should ignore when attribute order changes" do changes = added_attrs.at('p').diff(changed_attr_order.at('p')).to_a expect(changes.all? { |change| change[0] == ' ' }).to be_truthy end it "should determine when attributes are added" do changes = doc.at('p').diff(added_attr.at('p')).to_a expect(changes.length).to eq(3) expect(changes[0][0]).to eq(' ') expect(changes[0][1]).to eq(doc.at('p')) expect(changes[1][0]).to eq('+') expect(changes[1][1]).to eq(added_attr.at('//p/@id')) expect(changes[2][0]).to eq(' ') expect(changes[2][1]).to eq(doc.at('//p/text()')) end it "should determine when text nodes differ" do changes = doc.at('p').diff(changed_text.at('p')).to_a expect(changes.length).to eq(3) expect(changes[0][0]).to eq(' ') expect(changes[0][1]).to eq(doc.at('p')) expect(changes[1][0]).to eq('-') expect(changes[1][1]).to eq(doc.at('//p/text()')) expect(changes[2][0]).to eq('+') expect(changes[2][1]).to eq(changed_text.at('//p/text()')) end it "should determine when element names differ" do changes = doc.at('div').diff(changed_element.at('div')).to_a expect(changes.length).to eq(3) expect(changes[0][0]).to eq(' ') expect(changes[0][1]).to eq(doc.at('div')) expect(changes[1][0]).to eq('-') expect(changes[1][1]).to eq(doc.at('p')) expect(changes[2][0]).to eq('+') expect(changes[2][1]).to eq(changed_element.at('span')) end it "should determine when attribute names differ" do changes = added_attr.at('p').diff(changed_attr_name.at('p')).to_a expect(changes.length).to eq(4) expect(changes[0][0]).to eq(' ') expect(changes[0][1]).to eq(added_attr.at('p')) expect(changes[1][0]).to eq('-') expect(changes[1][1]).to eq(added_attr.at('//p/@id')) expect(changes[2][0]).to eq('+') expect(changes[2][1]).to eq(changed_attr_name.at('//p/@i')) expect(changes[3][0]).to eq(' ') expect(changes[3][1]).to eq(added_attr.at('//p/text()')) end it "should determine when attribute values differ" do changes = added_attr.at('p').diff(changed_attr_value.at('p')).to_a expect(changes.length).to eq(4) expect(changes[0][0]).to eq(' ') expect(changes[0][1]).to eq(added_attr.at('p')) expect(changes[1][0]).to eq('-') expect(changes[1][1]).to eq(added_attr.at('//p/@id')) expect(changes[2][0]).to eq('+') expect(changes[2][1]).to eq(changed_attr_value.at('//p/@id')) expect(changes[3][0]).to eq(' ') expect(changes[3][1]).to eq(added_attr.at('//p/text()')) end it "should determine when text nodes are removed" do changes = added_text.at('div').diff(removed_text.at('div')).to_a expect(changes.length).to eq(4) expect(changes[0][0]).to eq(' ') expect(changes[0][1]).to eq(added_text.at('div')) expect(changes[1][0]).to eq(' ') expect(changes[1][1]).to eq(added_text.at('p')) expect(changes[2][0]).to eq(' ') expect(changes[2][1]).to eq(added_text.at('//div/text()')) expect(changes[3][0]).to eq('-') expect(changes[3][1]).to eq(added_text.at('//p/text()')) end it "should determine when elements are removed" do changes = added_element.at('div').diff(removed_element.at('div')).to_a expect(changes.length).to eq(3) expect(changes[0][0]).to eq(' ') expect(changes[0][1]).to eq(added_element.at('div')) expect(changes[1][0]).to eq('-') expect(changes[1][1]).to eq(added_element.at('//p[1]')) expect(changes[2][0]).to eq('-') expect(changes[2][1]).to eq(added_element.at('//p[2]')) end it "should ignore when attributes change order" do end it "should determine when attributes are removed" do changes = added_attr.at('div').diff(removed_attr.at('div')).to_a expect(changes.length).to eq(4) expect(changes[0][0]).to eq(' ') expect(changes[0][1]).to eq(added_attr.at('div')) expect(changes[1][0]).to eq(' ') expect(changes[1][1]).to eq(added_attr.at('p')) expect(changes[2][0]).to eq('-') expect(changes[2][1]).to eq(added_attr.at('//p/@id')) expect(changes[3][0]).to eq(' ') expect(changes[3][1]).to eq(added_attr.at('//p/text()')) end context ":added" do it "should determine only when text nodes are added" do changes = doc.at('div').diff(added_text.at('div'), :added => true).to_a expect(changes.length).to eq(1) expect(changes[0][0]).to eq('+') expect(changes[0][1]).to eq(added_text.at('//div/text()')) end it "should determine only when elements are added" do changes = doc.at('div').diff(added_element.at('div'), :added => true).to_a expect(changes.length).to eq(1) expect(changes[0][0]).to eq('+') expect(changes[0][1]).to eq(added_element.at('//div/p[2]')) end it "should determine only when attributes are added" do changes = doc.at('div').diff(added_attr.at('div'), :added => true).to_a expect(changes.length).to eq(1) expect(changes[0][0]).to eq('+') expect(changes[0][1]).to eq(added_attr.at('//p/@id')) end end context ":removed" do it "should determine only when text nodes are removed" do changes = doc.at('div').diff(removed_text.at('div'), :removed => true).to_a expect(changes.length).to eq(1) expect(changes[0][0]).to eq('-') expect(changes[0][1]).to eq(doc.at('//p/text()')) end it "should determine only when elements are removed" do changes = doc.at('div').diff(removed_element.at('div'), :removed => true).to_a expect(changes.length).to eq(1) expect(changes[0][0]).to eq('-') expect(changes[0][1]).to eq(doc.at('//div/p')) end it "should determine only when attributes are removed" do changes = added_attr.at('div').diff(removed_attr.at('div'), :removed => true).to_a expect(changes.length).to eq(1) expect(changes[0][0]).to eq('-') expect(changes[0][1]).to eq(added_attr.at('//p/@id')) end end end
ruby
MIT
ea873edceb4e42fcdfc5a729ba899dff6ee68d80
2026-01-04T17:49:08.631513Z
false
postmodern/nokogiri-diff
https://github.com/postmodern/nokogiri-diff/blob/ea873edceb4e42fcdfc5a729ba899dff6ee68d80/spec/spec_helper.rb
spec/spec_helper.rb
require 'rspec' require 'simplecov' SimpleCov.start
ruby
MIT
ea873edceb4e42fcdfc5a729ba899dff6ee68d80
2026-01-04T17:49:08.631513Z
false
postmodern/nokogiri-diff
https://github.com/postmodern/nokogiri-diff/blob/ea873edceb4e42fcdfc5a729ba899dff6ee68d80/lib/nokogiri/diff.rb
lib/nokogiri/diff.rb
# frozen_string_literal: true require_relative 'diff/xml' require_relative 'diff/version'
ruby
MIT
ea873edceb4e42fcdfc5a729ba899dff6ee68d80
2026-01-04T17:49:08.631513Z
false
postmodern/nokogiri-diff
https://github.com/postmodern/nokogiri-diff/blob/ea873edceb4e42fcdfc5a729ba899dff6ee68d80/lib/nokogiri/diff/version.rb
lib/nokogiri/diff/version.rb
# frozen_string_literal: true module Nokogiri module Diff # nokogiri-diff version VERSION = '0.3.0' end end
ruby
MIT
ea873edceb4e42fcdfc5a729ba899dff6ee68d80
2026-01-04T17:49:08.631513Z
false