Class: MoneyAttribute::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/money_attribute/parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(currency = MoneyAttribute.default_currency) ⇒ Parser

Returns a new instance of Parser.



5
6
7
# File 'lib/money_attribute/parser.rb', line 5

def initialize(currency = MoneyAttribute.default_currency)
  @default_currency = currency
end

Instance Method Details

#parse(amount, currency = @default_currency) ⇒ Object Also known as: call



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/money_attribute/parser.rb', line 9

def parse(amount, currency = @default_currency)
  currency = ::Mint::Currency.resolve!(currency)
  case amount
  when NilClass    then nil
  when Numeric     then ::Mint::Money.from(amount, currency)
  when String      then ::Mint::Money.from(amount.to_r, currency)
  when ::Mint::Money
    return amount if amount.currency == currency

    raise TypeError, "Cannot automatically convert #{amount} to #{currency.code}"
  else
    ::Mint.parse(amount, currency)
  end
end