Module: Money::Helpers

Extended by:
Helpers
Included in:
Helpers
Defined in:
lib/money/helpers.rb

Constant Summary collapse

DECIMAL_ZERO =
BigDecimal(0).freeze
MAX_DECIMAL =
21

Instance Method Summary collapse

Instance Method Details

#value_to_currency(currency) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/money/helpers.rb', line 36

def value_to_currency(currency)
  case currency
  when Money::Currency, Money::NullCurrency
    currency
  when nil, ''
    default = Money::Config.current.currency
    raise(Money::Currency::UnknownCurrency, 'missing currency') if default.nil? || default == ''
    value_to_currency(default)
  when 'xxx', 'XXX'
    Money::NULL_CURRENCY
  when String
    Currency.find!(currency)
  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
      BigDecimal(num)
    else
      raise ArgumentError, "could not parse as decimal #{num.inspect}"
    end
  return DECIMAL_ZERO if value.sign == BigDecimal::SIGN_NEGATIVE_ZERO
  value
end