Sha256: 06e55db383aad90de390d90e72e9e098ac1a58561bcadee56908d3bce2794ce3

Contents?: true

Size: 1.02 KB

Versions: 8

Compression:

Stored size: 1.02 KB

Contents

module Schemacop
  class HashValidator < NodeSupportingField
    register symbols: :hash, klasses: Hash

    def validate(data, collector)
      super

      if data.is_a? ActiveSupport::HashWithIndifferentAccess
        allowed_fields = @fields.keys.map { |k| k.is_a?(String) ? k.to_sym : k }
        data_keys = data.keys.map { |k| k.is_a?(String) ? k.to_sym : k }

        # If the same key is specified in the schema as string and symbol, we
        # definitely expect a Ruby hash and not one with indifferent access
        if @fields.keys.length != Set.new(allowed_fields).length
          fail Exceptions::ValidationError, 'Hash expected, but got ActiveSupport::HashWithIndifferentAccess.'
        end
      else
        allowed_fields = @fields.keys
        data_keys = data.keys
      end

      obsolete_keys = data_keys - allowed_fields

      collector.error "Obsolete keys: #{obsolete_keys.inspect}." if obsolete_keys.any?

      @fields.values.each do |field|
        field.validate(data, collector)
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
schemacop-2.4.3 lib/schemacop/validator/hash_validator.rb
schemacop-2.4.2 lib/schemacop/validator/hash_validator.rb
schemacop-2.4.1 lib/schemacop/validator/hash_validator.rb
schemacop-2.4.0 lib/schemacop/validator/hash_validator.rb
schemacop-2.3.2 lib/schemacop/validator/hash_validator.rb
schemacop-2.3.1 lib/schemacop/validator/hash_validator.rb
schemacop-2.3.0 lib/schemacop/validator/hash_validator.rb
schemacop-2.2.0 lib/schemacop/validator/hash_validator.rb