Class: MoneyAttribute::Converter

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

Overview

:nodoc:

Constant Summary collapse

DEFAULT =
new.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(currency = nil) ⇒ Converter

Initializes a converter with an optional fixed currency.



9
10
11
# File 'lib/money_attribute/converter.rb', line 9

def initialize(currency = nil)
  @static_currency = currency
end

Class Method Details

.defaultObject

Returns the shared default converter instance.



14
15
16
# File 'lib/money_attribute/converter.rb', line 14

def self.default
  DEFAULT
end

Instance Method Details

#parse(amount) ⇒ Object Also known as: call

Converts raw input into a Money value.



19
20
21
22
23
24
25
26
27
# File 'lib/money_attribute/converter.rb', line 19

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