Class: Schash::Schema::Rule::Hash

Inherits:
Base
  • Object
show all
Defined in:
lib/schash/schema/rule/hash.rb

Instance Method Summary collapse

Methods inherited from Base

#optional?

Constructor Details

#initialize(schema_hash) ⇒ Hash

Returns a new instance of Hash.



5
6
7
# File 'lib/schash/schema/rule/hash.rb', line 5

def initialize(schema_hash)
  @schema_hash = schema_hash
end

Instance Method Details

#validate(target, position = []) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/schash/schema/rule/hash.rb', line 9

def validate(target, position = [])
  @schema_hash.map do |key, rule|
    if rule.is_a?(::Hash)
      rule = self.class.new(rule)
    end

    found_key = [key.to_s, key.to_sym].find do |k|
      target.has_key?(k)
    end

    if found_key
      rule.validate(target[found_key], position + [key.to_s])
    else
      unless rule.optional?
        Error.new(position + [key.to_s], "is required but missing")
      end
    end
  end.flatten.compact
end