class ExchangeRates::Rate

Constants

BASE_CURRENCY
CUSTOMS_VALUE_FALLBACK_CURRENCY
NOT_SUPPORTED_CURRENCIES

NB: to update the list of not supported currencies, run: Country.all.map(&:currency_code).uniq - Money::Currency.table.map{|c| c.to_s.upcase}

Public Class Methods

convert(amount, from_currency, to_currency = BASE_CURRENCY) click to toggle source
# File lib/exchange_rates/rate.rb, line 14
def self.convert(amount, from_currency, to_currency = BASE_CURRENCY)
  case
  when amount == 0
    0
  when to_currency == from_currency
    amount
  when to_currency == BASE_CURRENCY
    amount * get_rate(from_currency)
  else
    amount * (get_rate(from_currency) / get_rate(to_currency))
  end
end
get_rate(currency) click to toggle source
# File lib/exchange_rates/rate.rb, line 27
def self.get_rate(currency)
  return 1 if currency == BASE_CURRENCY
  cached = Rails.cache.fetch("#{currency.downcase}_to_#{BASE_CURRENCY.downcase}", expires_in: 1.day, race_condition_ttl: 5) do
    where(from_currency: currency).first.rate_to_base_currency
  end
  cached || where(from_currency: currency).first.rate_to_base_currency
end