Class: Schemacop::HashValidator

Inherits:
NodeSupportingField show all
Defined in:
lib/schemacop/validator/hash_validator.rb

Instance Attribute Summary

Attributes inherited from NodeSupportingField

#fields

Attributes inherited from Node

#options

Instance Method Summary collapse

Methods inherited from NodeSupportingField

#initialize, #opt!, #opt?, #req!, #req?

Methods inherited from NodeWithBlock

block_method, #exec_block

Methods inherited from Node

build, class_matches?, clear_klasses, clear_symbols, #exec_block, #initialize, klass, option, #option, #option?, register, #resolve_type_klass, symbol, symbol_matches?, #type_filter_matches?, #type_label, #type_matches?, type_matches?

Constructor Details

This class inherits a constructor from Schemacop::NodeSupportingField

Instance Method Details

#validate(data, collector) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/schemacop/validator/hash_validator.rb', line 7

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

  unless option?(:allow_obsolete_keys)
    collector.error "Obsolete keys: #{obsolete_keys.inspect}." if obsolete_keys.any?
  end

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