Class: MoneyAttribute::Converter

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(currency = nil) ⇒ Converter

Initializes a converter with an optional fixed currency.

Parameters:



17
18
19
# File 'lib/money_attribute/converter.rb', line 17

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

Class Method Details

.defaultConverter

Returns the shared default converter instance.

Returns:

  • (Converter)

    the frozen, process-wide converter



24
25
26
# File 'lib/money_attribute/converter.rb', line 24

def self.default
  DEFAULT
end

Instance Method Details

#parse(amount) ⇒ Mint::Money? Also known as: call

Converts raw input into a Mint::Money value.

Parameters:

Returns:

  • (Mint::Money, nil)

    Mint::Money for numeric and string input, the input itself for Mint::Money and nil

Raises:

  • (ArgumentError)

    for unsupported input types



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