Class: ActiveModel::Validations::ArrayValidator
- Inherits:
-
EachValidator
- Object
- EachValidator
- ActiveModel::Validations::ArrayValidator
- Defined in:
- lib/can_has_validations/validators/array_validator.rb
Direct Known Subclasses
Defined Under Namespace
Modules: DefaultKeys
Instance Attribute Summary collapse
-
#validators ⇒ Object
readonly
Returns the value of attribute validators.
Instance Method Summary collapse
-
#initialize(options) ⇒ ArrayValidator
constructor
A new instance of ArrayValidator.
- #validate_each(record, attribute, array_values) ⇒ Object
- #validate_one(validator, record, attribute, value) ⇒ Object
Constructor Details
#initialize(options) ⇒ ArrayValidator
Returns a new instance of ArrayValidator.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/can_has_validations/validators/array_validator.rb', line 40 def initialize() record_class = [:class] super record_class.extend DefaultKeys defaults = @options.dup validations = defaults.slice!(*record_class.send(:_validates_default_keys), :attributes) raise ArgumentError, "You need to supply at least one validation for :#{kind}" if validations.empty? defaults[:attributes] = attributes @validators = validations.map do |key, | next unless if (cond_keys = ().keys & %i(if on unless)).any? raise ArgumentError, ":#{kind} does not support conditionals on sub-validators - found on #{key}: #{cond_keys.map(&:inspect).join(', ')}" end key = "#{key.to_s.camelize}Validator" begin klass = key.include?("::".freeze) ? key.constantize : record_class.const_get(key) rescue NameError raise ArgumentError, "Unknown validator: '#{key}'" end klass.new(defaults.merge(()).except(:if, :on, :unless)) end end |
Instance Attribute Details
#validators ⇒ Object (readonly)
Returns the value of attribute validators.
38 39 40 |
# File 'lib/can_has_validations/validators/array_validator.rb', line 38 def validators @validators end |
Instance Method Details
#validate_each(record, attribute, array_values) ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/can_has_validations/validators/array_validator.rb', line 71 def validate_each(record, attribute, array_values) @validators.each do |validator| error_count = count_errors(record) Array(array_values).each do |value| validate_one(validator, record, attribute, value) # to avoid repeating error messages, stop after a single error unless validator.[:multiple_errors] break if error_count != count_errors(record) end end end end |
#validate_one(validator, record, attribute, value) ⇒ Object
86 87 88 89 90 91 |
# File 'lib/can_has_validations/validators/array_validator.rb', line 86 def validate_one(validator, record, attribute, value) unless validator.is_a?(ExistenceValidator) return if (value.nil? && validator.[:allow_nil]) || (value.blank? && validator.[:allow_blank]) end validator.validate_each(record, attribute, value) end |