Method: Money::Parsing::ClassMethods#parse

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

#parse(input, currency = nil) ⇒ Money

Parses the current string and converts it to a Money object. Excess characters will be discarded.

Examples:

'100'.to_money                #=> #<Money @cents=10000>
'100.37'.to_money             #=> #<Money @cents=10037>
'100 USD'.to_money            #=> #<Money @cents=10000, @currency=#<Money::Currency id: usd>>
'USD 100'.to_money            #=> #<Money @cents=10000, @currency=#<Money::Currency id: usd>>
'$100 USD'.to_money           #=> #<Money @cents=10000, @currency=#<Money::Currency id: usd>>
'hello 2000 world'.to_money   #=> #<Money @cents=200000 @currency=#<Money::Currency id: usd>>

Mismatching currencies

'USD 2000'.to_money("EUR")    #=> ArgumentError

Parameters:

  • input (String, #to_s)

    The input to parse.

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

    The currency format. The currency to set the resulting Money object to.

Returns:

Raises:

  • (ArgumentError)

    If any currency is supplied and given value doesn’t match the one extracted from the input string.

See Also:

  • Money.from_string


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/money/money/parsing.rb', line 36

def parse(input, currency = nil)
  i = input.to_s.strip

  # raise Money::Currency.table.collect{|c| c[1][:symbol]}.inspect

  # Check the first character for a currency symbol, alternatively get it
  # from the stated currency string
  c = if Money.assume_from_symbol && i =~ /^(\$|€|£)/
    case i
    when /^$/ then "USD"
    when /^€/ then "EUR"
    when /^£/ then "GBP"
    end
  else
    i[/[A-Z]{2,3}/]
  end

  # check that currency passed and embedded currency are the same,
  # and negotiate the final currency
  if currency.nil? and c.nil?
    currency = Money.default_currency
  elsif currency.nil?
    currency = c
  elsif c.nil?
    currency = currency
  elsif currency != c
    # TODO: ParseError
    raise ArgumentError, "Mismatching Currencies"
  end
  currency = Money::Currency.wrap(currency)

  cents = extract_cents(i, currency)
  new(cents, currency)
end