Class: Croesus::Validator::ManyValidator

Inherits:
Base show all
Defined in:
lib/croesus/validators/many_validator.rb

Instance Attribute Summary

Attributes inherited from Base

#name

Instance Method Summary collapse

Constructor Details

#initializeManyValidator

Returns a new instance of ManyValidator.



22
23
24
# File 'lib/croesus/validators/many_validator.rb', line 22

def initialize
  super('_many')  # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator)
end

Instance Method Details

#presence_error_messageObject



30
31
32
# File 'lib/croesus/validators/many_validator.rb', line 30

def presence_error_message
  "enumerable required"
end

#should_validate?(validation) ⇒ Boolean

Returns:



26
27
28
# File 'lib/croesus/validators/many_validator.rb', line 26

def should_validate?(validation)
  validation.is_a?(Croesus::Validations::Many)
end

#validate(key, value, validations, errors) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/croesus/validators/many_validator.rb', line 34

def validate(key, value, validations, errors)
  unless value.is_a?(Enumerable)
    errors[key] = presence_error_message
    return
  end

  element_errors = Array.new

  value.each_with_index do |element, i|
    ::Croesus.validator_for(validations.validation).validate(i, element, validations.validation, element_errors)
  end

  element_errors.each_with_index do |e, i|
    if e.respond_to?(:empty?) && e.empty?
      element_errors[i] = nil
    end
  end

  errors[key] = element_errors unless element_errors.all?(&:nil?)
end