Class: MoneyAttribute::AmountType

Inherits:
ActiveRecord::Type::Value
  • Object
show all
Defined in:
lib/money_attribute/type.rb

Overview

Base type for money amount attributes. Handles casting and validation.

Direct Known Subclasses

DecimalAmountType, IntegerAmountType

Instance Method Summary collapse

Instance Method Details

#assert_valid_value(value) ⇒ void

This method returns an undefined value.

Validates that the value is compatible with the fixed currency type.

Parameters:

  • value (Object)

    the value to validate

Raises:

  • (ArgumentError)

    when the value has a mismatched currency or is an unsupported type



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/money_attribute/type.rb', line 17

def assert_valid_value(value)
  case value
  when NilClass, Numeric, String then return
  when Mint::Money
    currency = MoneyAttribute.default_currency
    return if value.currency == currency

    message = "'#{value.inspect}' has different currency. Only #{currency.code} allowed."
  else
    message = "'#{value.inspect}' is not a valid type for the attribute."
  end
  raise ArgumentError, message
end

#cast(value) ⇒ Mint::Money, ...

Casts string input into a Mint::Money value.

Parameters:

Returns:

  • (Mint::Money, Numeric, nil)

    a Money value for strings, otherwise delegates to super



10
# File 'lib/money_attribute/type.rb', line 10

def cast(value) = value.is_a?(String) ? Money.parse(value, MoneyAttribute.default_currency) : super