Class: Money::Parser::LocaleAware

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

Class Method Summary collapse

Class Method Details

.decimal_separator_resolverObject

The Proc called to get the current locale decimal separator. In Rails apps this defaults to the same lookup ActionView’s number_to_currency helper will use to format the monetary amount for display.



10
11
12
# File 'lib/money/parser/locale_aware.rb', line 10

def decimal_separator_resolver
  @decimal_separator_resolver
end

.decimal_separator_resolver=(proc) ⇒ Object

Set the default Proc to determine the current locale decimal separator.

Examples:

Money::Parser::LocaleAware.decimal_separator_resolver =
  ->() { MyFormattingLibrary.current_locale.decimal.separator }


19
20
21
# File 'lib/money/parser/locale_aware.rb', line 19

def decimal_separator_resolver=(proc)
  @decimal_separator_resolver = proc
end

.parse(input, currency, strict: false, decimal_separator: decimal_separator_resolver&.call) ⇒ Money?

Parses an input string, normalizing some non-ASCII characters to their equivalent ASCII, then discarding any character that is not a digit, hyphen-minus or the decimal separator. To prevent user confusion, make sure that formatted Money strings can be parsed back into equivalent Money objects.

Parameters:

Returns:

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/money/parser/locale_aware.rb', line 32

def parse(input, currency, strict: false, decimal_separator: decimal_separator_resolver&.call)
  raise ArgumentError, "decimal separator cannot be nil" unless decimal_separator

  currency = Money::Helpers.value_to_currency(currency)
  return unless currency

  normalized_input = input
    .tr('-0-9.,、、', '-0-9.,,,')
    .gsub(/[^\d\-#{Regexp.escape(decimal_separator)}]/, '')
    .gsub(decimal_separator, '.')
  amount = BigDecimal(normalized_input, exception: false)
  if amount
    Money.new(amount, currency)
  elsif strict
    raise ArgumentError, "unable to parse input=\"#{input}\" currency=\"#{currency}\""
  end
end