Class: ActiveModel::Validations::QuantityValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/validates_quantity/quantity_validator.rb

Constant Summary collapse

CHECKS =
{ greater_than: :>, greater_than_or_equal_to: :>=,
equal_to: :==, less_than: :<, less_than_or_equal_to: :<=,
odd: :odd?, even: :even?, other_than: :!= }.freeze

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



8
9
10
11
12
13
14
15
# File 'lib/validates_quantity/quantity_validator.rb', line 8

def check_validity!
  keys = CHECKS.keys - [:odd, :even]
  options.slice(*keys).each do |option, value|
    unless value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol)
      raise ArgumentError, ":#{option} must be a number, a symbol or a proc"
    end
  end
end

#validate_each(record, attr_name, associations) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/validates_quantity/quantity_validator.rb', line 17

def validate_each(record, attr_name, associations)
  return if options[:allow_blank] and associations.allow_blank?

  value = associations.size
  options.slice(*CHECKS.keys).each do |option, option_value|
    case option
      when :odd, :even
        unless value.to_i.send(CHECKS[option])
          record.errors.add(attr_name, option, filtered_options(value))
        end
      else
        case option_value
          when Proc
            option_value = option_value.call(record)
          when Symbol
            option_value = record.send(option_value)
        end

        unless value.send(CHECKS[option], option_value)
          record.errors.add(attr_name, option, filtered_options(value).merge!(count: option_value))
        end
    end
  end
end