Class: Monetize::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/monetize/parser.rb

Constant Summary collapse

CURRENCY_SYMBOLS =
{
  '$'  => 'USD',
  ''  => 'EUR',
  '£'  => 'GBP',
  ''  => 'GBP',
  'R$' => 'BRL',
  'RM' => 'MYR',
  'Rp' => 'IDR',
  'R'  => 'ZAR',
  '¥'  => 'JPY',
  'C$' => 'CAD',
  ''  => 'AZN',
  '' => 'CNY',
  '' => 'CZK',
  'Ft' => 'HUF',
  ''  => 'INR',
  ''  => 'RUB',
  ''  => 'TRY',
  ''  => 'UAH',
  'Fr' => 'CHF',
  '' => 'PLN',
  ''  => 'KZT',
  ""  => 'KRW',
  'S$' => 'SGD',
  'HK$'=> 'HKD',
  'NT$'=> 'TWD',
  ''  => 'PHP',
}
MULTIPLIER_SUFFIXES =
{ 'K' => 3, 'M' => 6, 'B' => 9, 'T' => 12 }
MULTIPLIER_REGEXP =
Regexp.new(format('^(.*?\d)(%s)\b([^\d]*)$', MULTIPLIER_SUFFIXES.keys.join('|')), 'i')
DEFAULT_DECIMAL_MARK =
'.'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(input, fallback_currency = Money.default_currency, options = {}) ⇒ Parser

Returns a new instance of Parser.



40
41
42
43
44
# File 'lib/monetize/parser.rb', line 40

def initialize(input, fallback_currency = Money.default_currency, options = {})
  @input = input.to_s.strip
  @fallback_currency = fallback_currency
  @options = options
end

Instance Method Details

#parseObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/monetize/parser.rb', line 46

def parse
  currency = Money::Currency.wrap(parse_currency)

  multiplier_exp, input = extract_multiplier

  num = input.gsub(/(?:^#{currency.symbol}|[^\d.,'-]+)/, '')

  negative, num = extract_sign(num)

  num.chop! if num =~ /[\.|,]$/

  major, minor = extract_major_minor(num, currency)

  amount = to_big_decimal([major, minor].join(DEFAULT_DECIMAL_MARK))
  amount = apply_multiplier(multiplier_exp, amount)
  amount = apply_sign(negative, amount)

  [amount, currency]
end