Class: DataValidator::NumericalityValidator

Inherits:
BaseValidator show all
Defined in:
lib/validations/numericality.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? }.freeze

Instance Attribute Summary

Attributes inherited from BaseValidator

#errors, #name, #options, #value

Instance Method Summary collapse

Methods inherited from BaseValidator

#add_error, #initialize

Constructor Details

This class inherits a constructor from DataValidator::BaseValidator

Instance Method Details

#check_validity!Object



9
10
11
12
13
14
15
# File 'lib/validations/numericality.rb', line 9

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

#validateObject



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

def validate
  unless checked_value = parse_raw_value_as_a_number(value)
    add_error :not_a_number
    return
  end

  if options[:only_integer]
    unless checked_value = parse_raw_value_as_an_integer(value)
      add_error :not_an_integer
      return
    end
  end

  options.slice(*CHECKS.keys).each do |option, option_value|
    case option
    when :odd, :even
      unless checked_value.to_i.send(CHECKS[option])
        add_error option
      end
    else
      option_value = option_value.call(record) if option_value.is_a?(Proc)
      unless checked_value.send(CHECKS[option], option_value)
        add_error option, count: option_value
      end
    end
  end
end