lib/monetize.rb in monetize-0.3.0 vs lib/monetize.rb in monetize-0.4.0
- old
+ new
@@ -4,29 +4,32 @@
require "monetize/core_extensions"
require "monetize/version"
module Monetize
+ CURRENCY_SYMBOLS = {
+ "$" => "USD",
+ "€" => "EUR",
+ "£" => "GBP",
+ "R$" => "BRL",
+ "R" => "ZAR"
+ }
+
# Class methods
class << self
# @attr_accessor [true, false] assume_from_symbol Use this to enable the
# ability to assume the currency from a passed symbol
attr_accessor :assume_from_symbol
end
def self.parse(input, currency = Money.default_currency)
input = input.to_s.strip
- computed_currency = if assume_from_symbol && input =~ /^(\$|€|£)/
- case input
- when /^\$/ then "USD"
- when /^€/ then "EUR"
- when /^£/ then "GBP"
- end
- else
- input[/[A-Z]{2,3}/]
- end
+ computed_currency = compute_currency(input)
+ if not assume_from_symbol
+ computed_currency = input[/[A-Z]{2,3}/] || currency
+ end
currency = computed_currency || currency || Money.default_currency
currency = Money::Currency.wrap(currency)
fractional = extract_cents(input, currency)
@@ -140,7 +143,32 @@
end
cents += minor
negative ? cents * -1 : cents
+ end
+
+ private
+
+ def self.contains_currency_symbol?(amount)
+ currency_symbol_regex === amount
+ end
+
+ def self.compute_currency(amount)
+ if contains_currency_symbol?(amount)
+ matches = amount.match(currency_symbol_regex)
+ CURRENCY_SYMBOLS[matches[:symbol]]
+ else
+ amount[/[A-Z]{2,3}/]
+ end
+ end
+
+ def self.regex_safe_symbols
+ CURRENCY_SYMBOLS.keys.map { |key|
+ Regexp.escape(key)
+ }.join('|')
+ end
+
+ def self.currency_symbol_regex
+ /\A(?<symbol>#{regex_safe_symbols})/
end
end