class Money
Attributes
base[R]
rates[R]
amount[R]
currency[R]
Public Class Methods
conversion_rates(base, rates = {})
click to toggle source
# File lib/cute_exchange/money.rb, line 9 def conversion_rates(base, rates = {}) @base = base @rates = rates end
new(amount, currency)
click to toggle source
# File lib/cute_exchange/money.rb, line 17 def initialize(amount, currency) @amount = amount @currency = currency end
Public Instance Methods
*(arg)
click to toggle source
# File lib/cute_exchange/money.rb, line 45 def * arg perform_arithmetic(__method__, arg) end
+(arg)
click to toggle source
# File lib/cute_exchange/money.rb, line 33 def + arg perform_arithmetic(__method__, arg) end
-(arg)
click to toggle source
# File lib/cute_exchange/money.rb, line 37 def - arg perform_arithmetic(__method__, arg) end
/(arg)
click to toggle source
# File lib/cute_exchange/money.rb, line 41 def / arg perform_arithmetic(__method__, arg) end
<=>(arg)
click to toggle source
# File lib/cute_exchange/money.rb, line 49 def <=>(arg) BigDecimal(amount.to_s) <=> BigDecimal(arg.convert_to(currency).amount.to_s) end
convert_to(target)
click to toggle source
# File lib/cute_exchange/money.rb, line 22 def convert_to(target) return self if target == currency result = target == Money.base ? convert_to_base : convert_to_base * rate_by(target) self.class.new(result.to_s('F'), target) end
inspect(options={})
click to toggle source
# File lib/cute_exchange/money.rb, line 28 def inspect(options={}) precision = options[:precision] || 2 "#{"%.#{precision}f" % amount} #{currency}" end
Private Instance Methods
convert_to_base()
click to toggle source
# File lib/cute_exchange/money.rb, line 54 def convert_to_base return BigDecimal(amount.to_s) if currency == Money.base BigDecimal(amount.to_s) / Money.rates.fetch(currency) end
perform_arithmetic(operation, arg)
click to toggle source
# File lib/cute_exchange/money.rb, line 63 def perform_arithmetic(operation, arg) converted_amount = arg.is_a?(Numeric) ? arg : arg.convert_to(currency).amount new_amount = BigDecimal(amount.to_s).send(operation, BigDecimal(converted_amount.to_s)) self.class.new(new_amount.to_s('F'), currency) end
rate_by(currency)
click to toggle source
# File lib/cute_exchange/money.rb, line 59 def rate_by(currency) Money.rates.fetch(currency) end