Module: Philiprehberger::Money::Parsing
- Defined in:
- lib/philiprehberger/money/parsing.rb
Overview
Parsing formatted money strings back into Money objects
Class Method Summary collapse
-
.parse(input, currency: nil) ⇒ Money
Parse a formatted money string into a Money object.
Class Method Details
.parse(input, currency: nil) ⇒ Money
Parse a formatted money string into a Money object
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 |