Class: Ree::Contracts::ArrayValidator
- Inherits:
-
BaseValidator
- Object
- BaseValidator
- Ree::Contracts::ArrayValidator
- Defined in:
- lib/ree/contracts/validators/array_validator.rb
Instance Attribute Summary collapse
-
#validators ⇒ Object
readonly
Returns the value of attribute validators.
Attributes inherited from BaseValidator
Instance Method Summary collapse
- #call(value) ⇒ Object
-
#initialize(contract) ⇒ ArrayValidator
constructor
A new instance of ArrayValidator.
- #message(value, name, lvl = 1) ⇒ Object
- #to_s ⇒ Object
Methods included from Truncatable
Constructor Details
#initialize(contract) ⇒ ArrayValidator
Returns a new instance of ArrayValidator.
7 8 9 10 |
# File 'lib/ree/contracts/validators/array_validator.rb', line 7 def initialize(contract) super(contract) @validators = contract.map { |cont| Validators.fetch_for(cont) } end |
Instance Attribute Details
#validators ⇒ Object (readonly)
Returns the value of attribute validators.
5 6 7 |
# File 'lib/ree/contracts/validators/array_validator.rb', line 5 def validators @validators end |
Instance Method Details
#call(value) ⇒ Object
16 17 18 19 20 21 22 |
# File 'lib/ree/contracts/validators/array_validator.rb', line 16 def call(value) return false unless value.is_a?(Array) && value.length == validators.length value.zip(validators).all? do |val, validator| validator.call(val) end end |
#message(value, name, lvl = 1) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/ree/contracts/validators/array_validator.rb', line 24 def (value, name, lvl = 1) unless value.is_a?(Array) return "expected Array, got #{value.class} => #{truncate(value.inspect)}" end unless value.length == validators.length return "expected to have #{validators.length} #{pluralize(validators.length, 'item', 'items')}, got #{value.length} #{pluralize(value.length, 'item', 'items')} => #{truncate(value.inspect)}" end errors = [] sps = " " * lvl value.zip(validators).each_with_index do |(val, validator), idx| next if validator.call(val) msg = validator.(val, "#{name}[#{idx}]", lvl + 1) errors << "\n\t#{sps} - #{name}[#{idx}]: #{msg}" if errors.size > 3 errors << "\n\t#{sps} - ..." break end end errors.join end |
#to_s ⇒ Object
12 13 14 |
# File 'lib/ree/contracts/validators/array_validator.rb', line 12 def to_s "[#{validators.map(&:to_s).join(', ')}]" end |