Class: HashValidator::Validator::HashValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/hash_validator/validators/hash_validator.rb

Instance Attribute Summary

Attributes inherited from Base

#name

Instance Method Summary collapse

Methods inherited from Base

#presence_error_message

Constructor Details

#initializeHashValidator

Returns a new instance of HashValidator.



2
3
4
# File 'lib/hash_validator/validators/hash_validator.rb', line 2

def initialize
  super('hash')
end

Instance Method Details

#should_validate?(rhs) ⇒ Boolean

Returns:

  • (Boolean)


6
7
8
# File 'lib/hash_validator/validators/hash_validator.rb', line 6

def should_validate?(rhs)
  rhs.is_a?(Hash)
end

#validate(key, value, validations, errors) ⇒ Object



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

def validate(key, value, validations, errors)
  # Validate hash
  unless value.is_a?(Hash)
    errors[key] = presence_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