Class: ActiveModel::Validations::ArrayValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/can_has_validations/validators/array_validator.rb

Direct Known Subclasses

HashKeysValidator, HashValuesValidator

Defined Under Namespace

Modules: DefaultKeys

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ ArrayValidator

Returns a new instance of ArrayValidator.

Raises:

  • (ArgumentError)


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(options)
  record_class = options[: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, sub_options|
    next unless sub_options

    if (cond_keys = _parse_validates_options(sub_options).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(_parse_validates_options(sub_options)).except(:if, :on, :unless))
  end
end

Instance Attribute Details

#validatorsObject (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.options[: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.options[:allow_nil]) || (value.blank? && validator.options[:allow_blank])
  end
  validator.validate_each(record, attribute, value)
end