Class: Launchpad::PrecisionValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/launchpad/precision_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/launchpad/precision_validator.rb', line 6

def validate_each(record, attribute, value)
  return unless options.key?(:less_than_or_eq_to) && value.present?

  precision = if options[:less_than_or_eq_to].respond_to?(:call)
                options[:less_than_or_eq_to].call(record)
              else
                options[:less_than_or_eq_to]
              end

  unless value.is_a?(Numeric)
    record.errors.add(attribute, 'must be a number')
    return
  end

  unless value.round(precision) == value
    record.errors.add(attribute, "precision must be less than or equal to #{precision}")
  end
end