Class: MoneyRails::ActiveModel::MoneyValidator
- Inherits:
-
ActiveModel::Validations::NumericalityValidator
- Object
- ActiveModel::Validations::NumericalityValidator
- MoneyRails::ActiveModel::MoneyValidator
- Defined in:
- lib/money-rails/active_model/validator.rb
Defined Under Namespace
Classes: Details
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attr, _value) ⇒ Object
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/money-rails/active_model/validator.rb', line 14 def validate_each(record, attr, _value) subunit_attr = record.class.monetized_attributes[attr.to_s] currency = record.public_send("currency_for_#{attr}") # 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 [:allow_nil] && raw_value.nil? # Set this before we modify raw_value below. stringy = raw_value.present? && !raw_value.is_a?(Numeric) && !raw_value.is_a?(Money) if stringy # TODO: This is supporting legacy behaviour where a symbol can come from a i18n locale, # however practical implications of that are most likely non-existent symbol = lookup(:symbol, currency) || currency.symbol # remove currency symbol raw_value = raw_value.to_s.gsub(symbol, "") end # Cache abs_raw_value before normalizing because it's used in # many places and relies on the original raw_value. details = generate_details(raw_value, currency) normalized_raw_value = normalize(details) super(record, attr, normalized_raw_value) return unless stringy return if record_already_has_error?(record, attr, normalized_raw_value) add_error!(record, attr, details) if value_has_too_many_decimal_points(details) || thousand_separator_after_decimal_mark(details) || invalid_thousands_separation(details) end |