lib/danconia/money.rb in danconia-0.2.1 vs lib/danconia/money.rb in danconia-0.2.2

- old
+ new

@@ -6,21 +6,25 @@ include Comparable attr_reader :amount, :currency, :decimals, :exchange def initialize amount, currency_code = nil, decimals: 2, exchange: Danconia.config.default_exchange @decimals = decimals - @amount = parse(amount) + @amount = parse amount @currency = Currency.find(currency_code || Danconia.config.default_currency, exchange) @exchange = exchange end - def to_s + def format decimals: @decimals ActiveSupport::NumberHelper.number_to_currency amount, precision: decimals, unit: currency.symbol end + def to_s + format + end + def inspect - "#<#{self.class.name} #{amount} #{currency.code}>" + "#{amount} #{currency.code}" end def == other if other.is_a?(Money) amount == other.amount && currency == other.currency @@ -41,15 +45,21 @@ other = other.exchange_to(currency).amount if other.is_a? Money amount <=> other end def exchange_to other_currency - other_currency = Currency.find(other_currency, exchange) - rate = exchange_rate(currency, other_currency) + other_currency = other_currency.presence && Currency.find(other_currency, exchange) || currency + rate = exchange_rate_to(other_currency.code) clone_with amount * rate, other_currency end + def exchange_rate_to to + from = currency.code + return 1 if from == to + exchange.rate from, to + end + %w(+ - * /).each do |op| class_eval <<-EOR, __FILE__, __LINE__ + 1 def #{op} other other = other.exchange_to(currency).amount if other.is_a? Money clone_with amount #{op} other @@ -63,10 +73,14 @@ def in_cents (self * 100).round end + def default_currency? + currency.code == Danconia.config.default_currency + end + def method_missing method, *args if @amount.respond_to? method @amount.send method, *args else super @@ -78,18 +92,13 @@ end private def parse object - BigDecimal(object.to_s) rescue BigDecimal('0') + BigDecimal(object.to_s) rescue BigDecimal(0) end def clone_with amount, currency = @currency Money.new amount, currency, decimals: decimals, exchange: exchange - end - - def exchange_rate from, to - return 1 if from == to - exchange.rate from.code, to.code end end end