Class: Compel::Validators::HashKeysValidator

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

Instance Attribute Summary collapse

Attributes inherited from Base

#errors, #input, #output, #schema

Instance Method Summary collapse

Methods inherited from Base

#valid?, validate

Constructor Details

#initialize(input, schemas) ⇒ HashKeysValidator

Returns a new instance of HashKeysValidator.



69
70
71
72
73
74
75
# File 'lib/compel/validators/hash_validator.rb', line 69

def initialize(input, schemas)
  super

  @output = {}
  @errors = Errors.new
  @schemas = schemas
end

Instance Attribute Details

#schemasObject (readonly)

Returns the value of attribute schemas.



67
68
69
# File 'lib/compel/validators/hash_validator.rb', line 67

def schemas
  @schemas
end

Instance Method Details

#validateObject



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/compel/validators/hash_validator.rb', line 77

def validate
  schemas.keys.each do |key|
    value = output[key].nil? ? input[key] : output[key]

    validator = TypeValidator.validate(value, schemas[key])

    unless validator.output.nil?
      output[key] = validator.output
    end

    unless validator.valid?
      errors.add(key, validator.errors)
      next
    end

    if schemas[key].type == Coercion::Hash &&
        (schemas[key].required? ||
          !input[key].nil?)

      hash_validator = HashValidator.validate(input[key], schemas[key])

      errors.add(key, hash_validator.errors)
      output[key] = hash_validator.output
    end

  end

  self
end