Class: MoneyAttribute::Converter
- Inherits:
-
Object
- Object
- MoneyAttribute::Converter
- Defined in:
- lib/money_attribute/converter.rb
Overview
Converts raw attribute input into Mint::Money values.
Used in two roles: as the :converter option of composed_of (composite
attributes) and as the normalizer block for money_amount (single-column
attributes). Accepts Mint::Money, numeric, string, and nil input.
Constant Summary collapse
- DEFAULT =
new.freeze
Class Method Summary collapse
-
.default ⇒ Converter
Returns the shared default converter instance.
Instance Method Summary collapse
-
#initialize(currency = nil) ⇒ Converter
constructor
Initializes a converter with an optional fixed currency.
-
#parse(amount) ⇒ Mint::Money?
(also: #call)
Converts raw input into a
Mint::Moneyvalue.
Constructor Details
#initialize(currency = nil) ⇒ Converter
Initializes a converter with an optional fixed currency.
17 18 19 |
# File 'lib/money_attribute/converter.rb', line 17 def initialize(currency = nil) @static_currency = currency end |
Class Method Details
Instance Method Details
#parse(amount) ⇒ Mint::Money? Also known as: call
Converts raw input into a Mint::Money value.
34 35 36 37 38 39 40 41 42 |
# File 'lib/money_attribute/converter.rb', line 34 def parse(amount) currency = @static_currency || MoneyAttribute.default_currency case amount when Money, NilClass then amount when Numeric then Money.from(amount, currency) when String then Money.parse(amount, currency) else raise ArgumentError, "Cannot convert #{amount.inspect} (#{amount.class}) to Money" end end |