Class: Dry::Validation::Schema::Key

Inherits:
BasicObject
Defined in:
lib/dry/validation/schema/key.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, rules, &block) ⇒ Key

Returns a new instance of Key.



9
10
11
12
# File 'lib/dry/validation/schema/key.rb', line 9

def initialize(name, rules, &block)
  @name = name
  @rules = rules
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object (private)



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/dry/validation/schema/key.rb', line 29

def method_missing(meth, *args, &block)
  key_rule = [:key, [name, [:predicate, [meth, args]]]]

  if block
    val_rule = yield(Value.new(name))

    rules <<
      if val_rule.is_a?(::Array)
        Schema::Rule.new(name, [:and, [key_rule, [:set, [name, val_rule.map(&:to_ary)]]]])
      else
        Schema::Rule.new(name, [:and, [key_rule, val_rule.to_ary]])
      end
  else
    Schema::Rule.new(name, key_rule)
  end
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



7
8
9
# File 'lib/dry/validation/schema/key.rb', line 7

def name
  @name
end

#rulesObject (readonly)

Returns the value of attribute rules.



7
8
9
# File 'lib/dry/validation/schema/key.rb', line 7

def rules
  @rules
end

Instance Method Details

#optional(&block) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/dry/validation/schema/key.rb', line 14

def optional(&block)
  key_rule = key?

  val_rule = yield(Value.new(name))

  rules <<
    if val_rule.is_a?(::Array)
      Schema::Rule.new(name, [:implication, [key_rule.to_ary, [:set, [name, val_rule.map(&:to_ary)]]]])
    else
      Schema::Rule.new(name, [:implication, [key_rule.to_ary, val_rule.to_ary]])
    end
end