Module: Money::Helpers
- Defined in:
- lib/money/helpers.rb
Constant Summary collapse
- NUMERIC_REGEX =
/\A\s*[\+\-]?(\d+|\d*\.\d+)\s*\z/- DECIMAL_ZERO =
BigDecimal(0).freeze
- MAX_DECIMAL =
21
Class Method Summary collapse
- .string_to_decimal(num) ⇒ Object
- .value_to_currency(currency) ⇒ Object
- .value_to_decimal(num) ⇒ Object
Class Method Details
.string_to_decimal(num) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/money/helpers.rb', line 58 def string_to_decimal(num) if num =~ NUMERIC_REGEX return BigDecimal(num) end Money.deprecate("using Money.new('#{num}') is deprecated and will raise an ArgumentError in the next major release") begin BigDecimal(num) rescue ArgumentError DECIMAL_ZERO end end |
.value_to_currency(currency) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/money/helpers.rb', line 36 def value_to_currency(currency) case currency when Money::Currency, Money::NullCurrency currency when nil, '' default = Money.current_currency || Money.default_currency raise(ArgumentError, 'missing currency') if default.nil? || default == '' value_to_currency(default) when 'xxx', 'XXX' Money::NULL_CURRENCY when String begin Currency.find!(currency) rescue Money::Currency::UnknownCurrency => error Money.deprecate(error.) Money::NULL_CURRENCY end else raise ArgumentError, "could not parse as currency #{currency.inspect}" end end |
.value_to_decimal(num) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/money/helpers.rb', line 12 def value_to_decimal(num) value = case num when Money num.value when BigDecimal num when nil, 0, '' DECIMAL_ZERO when Integer BigDecimal(num) when Float BigDecimal(num, Float::DIG) when Rational BigDecimal(num, MAX_DECIMAL) when String string_to_decimal(num) else raise ArgumentError, "could not parse as decimal #{num.inspect}" end return DECIMAL_ZERO if value.sign == BigDecimal::SIGN_NEGATIVE_ZERO value end |