Class: WhittakerTech::Midas::Coin::Parser

Inherits:
Object
  • Object
show all
Defined in:
app/models/whittaker_tech/midas/coin/parser.rb

Overview

Parser coerces heterogeneous inputs into a Coin.

Accepted input types:

Accepted input types:

  • Coin: Returned as-is (no conversion)
  • Money: Wraps money.cents + money.currency.iso_code into a Coin
  • Numeric: Treated as a major-unit amount; currency_code required
  • String: Strips non-numeric characters; currency_code recommended

Numeric vs. Integer semantics

The Parser treats all Numeric inputs (including Integer) as major units (dollars, euros, etc.) and scales them to minor units using Money.from_amount. This differs from Coin#amount= and Coin.value, which expect minor units directly.

If you already have cents use Coin.value(2999, 'USD') instead.

Examples:

Coin.parse(Money.new(2999, 'USD'))          # => Coin(2999 USD)
Coin.parse(29.99, currency_code: 'USD')     # => Coin(2999 USD)
Coin.parse('$29.99')                        # => Coin(2999 USD)  (uses Money.default_currency)
Coin.parse('29.99', currency_code: 'USD')   # => Coin(2999 USD)

Since:

  • 0.1.0

Class Method Summary collapse

Class Method Details

.parse(value, currency_code: nil) ⇒ Coin

Parses a value into a Coin.

Parameters:

  • value (Coin, Money, Numeric, String)

    the value to parse

  • currency_code (String, nil) (defaults to: nil)

    required for bare Numeric and plain String values

Returns:

Raises:

  • (TypeError)

    if value is an unsupported type

  • (ArgumentError)

    if currency_code is required but not provided

Since:

  • 0.1.0



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'app/models/whittaker_tech/midas/coin/parser.rb', line 40

def parse(value, currency_code: nil)
  case value
  when WhittakerTech::Midas::Coin
    value
  when Money
    WhittakerTech::Midas::Coin.value(value.cents, value.currency.iso_code)
  when Numeric
    parse_numeric(value, currency_code)
  when String
    parse_string(value, currency_code)
  else
    raise TypeError, "Cannot convert #{value.class} to Coin"
  end
end