Class: EqualityValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/active_validation/validators/equality_validator.rb

Constant Summary collapse

OPERATORS =
{
  less_than: :<, less_than_or_equal_to: :<=, greater_than: :>, greater_than_or_equal_to: :>=,
  equal_to: :==, not_equal_to: :!=
}.freeze

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

rubocop:disable Metrics/LineLength



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/active_validation/validators/equality_validator.rb', line 9

def validate_each(record, attribute, value)
  to = options[:to]
  if to.nil?
    raise ArgumentError,
          'ArgumentError: missing ":to" attribute for comparison.'
  end

  operator = options[:operator]
  operators = OPERATORS.keys
  unless operators.include?(operator)
    raise ArgumentError,
          "Unknown operator: #{operator.inspect}. Valid operators are: #{operators.map(&:inspect).join(', ')}"
  end

  operator = OPERATORS[operator]
  unless value.send(operator, record.send(to))
    record.errors[attribute] <<
      (options[:message] || I18n.t('active_validation.errors.messages.equality', attr: to, operator: operator))
  end
end