lib/danconia/money.rb in danconia-0.2.9 vs lib/danconia/money.rb in danconia-0.3.0
- old
+ new
@@ -2,17 +2,17 @@
require 'danconia/errors/exchange_rate_not_found'
module Danconia
class Money
include Comparable
- attr_reader :amount, :currency, :decimals, :exchange
+ attr_reader :amount, :currency, :decimals
- def initialize amount, currency_code = nil, decimals: 2, exchange: Danconia.config.default_exchange
- @decimals = decimals
+ def initialize(amount, currency_code = nil, decimals: 2, exchange_opts: {})
@amount = parse amount
- @currency = Currency.find(currency_code || Danconia.config.default_currency, exchange)
- @exchange = exchange
+ @decimals = decimals
+ @currency = Currency.find(currency_code || Danconia.config.default_currency)
+ @exchange_opts = exchange_opts.reverse_merge(exchange: Danconia.config.default_exchange)
end
def format decimals: @decimals, **other_options
opts = other_options.reverse_merge precision: decimals, unit: currency.symbol
ActiveSupport::NumberHelper.number_to_currency amount, opts
@@ -39,27 +39,26 @@
def hash
[amount, currency].hash
end
def <=> other
- other = other.exchange_to(currency).amount if other.is_a? Money
- amount <=> other
+ amount <=> amount_exchanged_to_this_currency(other)
end
- def exchange_to other_currency, exchange: @exchange
- other_currency = other_currency.presence && Currency.find(other_currency, exchange) || currency
- rate = exchange.rate currency.code, other_currency.code
- clone_with amount * rate, other_currency, exchange
+ def exchange_to other_currency, **opts
+ opts = @exchange_opts.merge(opts)
+ other_currency = other_currency.presence && Currency.find(other_currency) || currency
+ rate = opts[:exchange].rate currency.code, other_currency.code, opts.except(:exchange)
+ clone_with amount * rate, other_currency, opts
end
- %w(+ - * /).each do |op|
- class_eval <<-EOR, __FILE__, __LINE__ + 1
+ %w[+ - * /].each do |op|
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{op} other
- other = other.exchange_to(currency, exchange: @exchange).amount if other.is_a? Money
- clone_with(amount #{op} other)
+ clone_with(amount #{op} amount_exchanged_to_this_currency(other))
end
- EOR
+ RUBY
end
def round *args
clone_with amount.round(*args)
end
@@ -92,10 +91,18 @@
def parse object
BigDecimal(object.to_s) rescue BigDecimal(0)
end
- def clone_with amount, currency = @currency, exchange = @exchange
- Money.new amount, currency, decimals: decimals, exchange: exchange
+ def clone_with amount, currency = @currency, exchange_opts = @exchange_opts
+ Money.new amount, currency, decimals: @decimals, exchange_opts: exchange_opts
+ end
+
+ def amount_exchanged_to_this_currency other
+ if other.is_a? Money
+ other.exchange_to(currency, @exchange_opts).amount
+ else
+ other
+ end
end
end
end