Class: NxtSchema::Validators::Attribute

Inherits:
Validator
  • Object
show all
Defined in:
lib/nxt_schema/validators/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Validator

register_as, #translate_error

Constructor Details

#initialize(method, expectation) ⇒ Attribute

Returns a new instance of Attribute.



4
5
6
7
# File 'lib/nxt_schema/validators/attribute.rb', line 4

def initialize(method, expectation)
  @method = method
  @expectation = expectation
end

Instance Attribute Details

#expectationObject (readonly)

Returns the value of attribute expectation.



10
11
12
# File 'lib/nxt_schema/validators/attribute.rb', line 10

def expectation
  @expectation
end

#methodObject (readonly)

Returns the value of attribute method.



10
11
12
# File 'lib/nxt_schema/validators/attribute.rb', line 10

def method
  @method
end

Instance Method Details

#buildObject

Query any attribute on a value with validator(:attribute, :size, ->(s) { s < 7 })



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/nxt_schema/validators/attribute.rb', line 14

def build
  lambda do |node, value|
    raise ArgumentError, "#{value} does not respond to query: #{method}" unless value.respond_to?(method)

    if expectation.call(value.send(method))
      true
    else
      node.add_error(
        translate_error(
          node.locale,
          attribute: value,
          attribute_name: method,
          value: value.send(method)
        )
      )
    end
  end
end