Module: Philiprehberger::Money::Parsing

Defined in:
lib/philiprehberger/money/parsing.rb

Overview

Parsing formatted money strings back into Money objects

Class Method Summary collapse

Class Method Details

.parse(input, currency: nil) ⇒ Money

Parse a formatted money string into a Money object

Parameters:

  • input (String)

    formatted money string (e.g. “$1,234.56”, “1.234,56 EUR”)

  • currency (Symbol, String, nil) (defaults to: nil)

    optional currency code override

Returns:

  • (Money)

    parsed money object

Raises:



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/philiprehberger/money/parsing.rb', line 13

def self.parse(input, currency: nil)
  str = input.to_s.strip
  raise ParseError, 'Cannot parse empty string as money' if str.empty?

  detected_currency = currency ? Currency.find(currency) : detect_currency(str)
  raise ParseError, "Cannot detect currency from: #{input}" unless detected_currency

  cleaned = extract_numeric(str, detected_currency)
  raise ParseError, "Cannot parse amount from: #{input}" if cleaned.empty?

  negative = str.match?(/^-/) || str.match?(/\(-?\d/)
  amount = BigDecimal(cleaned)
  amount = -amount if negative

  cents = (amount * detected_currency.subunit_to_unit).round(0, BigDecimal::ROUND_HALF_EVEN).to_i
  Money.new(cents, detected_currency.code)
end