Class: MoneyRails::ActiveModel::MoneyValidator

Inherits:
ActiveModel::Validations::NumericalityValidator
  • Object
show all
Defined in:
lib/money-rails/active_model/validator.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attr, _value) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
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
# File 'lib/money-rails/active_model/validator.rb', line 4

def validate_each(record, attr, _value)
  reset_memoized_variables!
  @record = record
  @attr = attr

  subunit_attr = @record.class.monetized_attributes[@attr.to_s]

  # WARNING: Currently this is only defined in ActiveRecord extension!
  before_type_cast = :"#{@attr}_money_before_type_cast"
  @raw_value = @record.try(before_type_cast)

  # If raw value is nil and changed subunit is nil, then
  # nil is a assigned value, else we should treat the
  # subunit value as the one assigned.
  if @raw_value.nil? && @record.public_send(subunit_attr)
    subunit_value = @record.public_send(subunit_attr)
    @raw_value = subunit_value.to_f / currency.subunit_to_unit
  end

  return if options[:allow_nil] && @raw_value.nil?

  # Set this before we modify @raw_value below.
  stringy = @raw_value.present? && !@raw_value.is_a?(Numeric)

  if stringy
    # remove currency symbol
    @raw_value = @raw_value.to_s.gsub(symbol, "")
  end

  normalize_raw_value!
  super(@record, @attr, @raw_value)

  if stringy and not @record.errors.added?(@attr, :not_a_number)
    add_error if
      value_has_too_many_decimal_points or
      thousand_separator_after_decimal_mark or
      invalid_thousands_separation
  end
end