class Money::Money

Attributes

default_currency[RW]
rates[RW]
amount[RW]
currency[RW]

Public Class Methods

conversion_rates(default_currency, rates) click to toggle source
# File lib/ruby_money/money.rb, line 8
def conversion_rates(default_currency, rates)
  @default_currency = default_currency
  @rates = rates.merge({ default_currency => 1 })
end
new(amount, currency) click to toggle source
# File lib/ruby_money/money.rb, line 14
def initialize(amount, currency)
  @amount = Float(amount)
  @currency = currency

  validate_currency!(currency)
end

Public Instance Methods

*(num) click to toggle source
# File lib/ruby_money/money.rb, line 45
def * (num)
  self.class.new(@amount * num, @currency)
end
+(other) click to toggle source
# File lib/ruby_money/money.rb, line 31
def + (other)
  other_amount = other_to_currency(other).amount
  self.class.new(@amount + other_amount, @currency)
end
-(other) click to toggle source
# File lib/ruby_money/money.rb, line 36
def - (other)
  other_amount = other_to_currency(other).amount
  self.class.new(@amount - other_amount, @currency)
end
/(num) click to toggle source
# File lib/ruby_money/money.rb, line 41
def / (num)
  self.class.new(@amount / num, @currency)
end
<(other) click to toggle source
# File lib/ruby_money/money.rb, line 53
def < (other)
  @amount < other_to_currency(other).amount
end
==(other) click to toggle source
# File lib/ruby_money/money.rb, line 49
def == (other)
  other_to_currency(other).amount == @amount
end
>(other) click to toggle source
# File lib/ruby_money/money.rb, line 57
def > (other)
  @amount > other_to_currency(other).amount
end
convert_to(currency) click to toggle source
# File lib/ruby_money/money.rb, line 25
def convert_to currency
  validate_currency!(currency)
  amount =  (amount_in_default_currency * rates[currency]).round(4)
  self.class.new(amount, currency)
end
inspect() click to toggle source
# File lib/ruby_money/money.rb, line 21
def inspect
  "#{sprintf('%.2f', @amount)} #{@currency}"
end

Private Instance Methods

amount_in_default_currency() click to toggle source
# File lib/ruby_money/money.rb, line 66
def amount_in_default_currency
  return @amount if @currency == default_currency
  @amount / rates[@currency]
end
default_currency() click to toggle source
# File lib/ruby_money/money.rb, line 75
def default_currency
  @default_currency ||= self.class.default_currency
end
other_to_currency(other) click to toggle source
# File lib/ruby_money/money.rb, line 62
def other_to_currency other
  other.currency == @currency ? other : other.convert_to(@currency)
end
rates() click to toggle source
# File lib/ruby_money/money.rb, line 71
def rates
  @rates ||= self.class.rates
end
validate_currency!(currency) click to toggle source
# File lib/ruby_money/money.rb, line 79
def validate_currency! currency
  raise ArgumentError, "#{currency} is no a valid currency" if rates[currency].nil?
end