Class: ActiveModel::Validations::SumOfValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/activemodel-validators/sum_of_validator.rb

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



4
5
6
7
8
# File 'lib/activemodel-validators/sum_of_validator.rb', line 4

def check_validity!
  unless options[:attr_names]
    raise ArgumentError, "must supply :attr_names option"
  end
end

#validate_each(record, attribute, value) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/activemodel-validators/sum_of_validator.rb', line 10

def validate_each(record, attribute, value)
  addends = options[:attr_names].map {|_| record[_] }
  return if value.blank?
  sum = addends.reject(&:blank?).sum
  unless value == sum
    record.errors.add(attribute, options[:message] || :sum_of,
                      options.merge(
                        attr_names: options[:attr_names].to_sentence,
                        addends: addends.join(' + '),
                        sum: sum,
                        value: value,
                      )
    )
  end
end