class Schemacop::V2::HashValidator

Public Instance Methods

validate(data, collector) click to toggle source
Calls superclass method
# File lib/schemacop/v2/validator/hash_validator.rb, line 8
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

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

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