Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/more_money/core_extensions.rb

Overview

Allows Writing of ‘100’.to_money for String types Excess characters will be discarded

'100'.to_money => #<Money @cents=10000>
'100.37'.to_money => #<Money @cents=10037>

Instance Method Summary collapse

Instance Method Details

#to_money(currency = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/more_money/core_extensions.rb', line 25

def to_money(currency = nil)
  # Get the currency
  matches = scan(/([A-Z]{2,3})/)
  currency ||= matches[0] ? matches[0][0] : MoreMoney::Money.default_currency
  
  # Get the cents amount
  matches = scan(/(\-?\d+(\.(\d+))?)/)
  cents = matches[0] ? (matches[0][0].to_f * 100) : nil
  
  MoreMoney::Money.new(cents, currency)
end

#to_price(opts = {}) ⇒ Object



37
38
39
40
41
# File 'lib/more_money/core_extensions.rb', line 37

def to_price(opts = {})
  money = to_money(opts[:currency])
  args = [opts[:tax_code], opts[:tax_inclusive]].compact
  Price.new(money.cents, money.currency, *args)
end