class Convertator::Converter

Attributes

provider[R]

Public Class Methods

new(provider = :cbr, accuracy = 10) { |self| ... } click to toggle source
# File lib/convertator/converter.rb, line 14
def initialize(provider = :cbr, accuracy = 10)
  @provider = load_provider(provider)
  @accuracy = accuracy
  @chain = [] << @provider
  yield(self) if block_given?
end

Public Instance Methods

add(middleware) click to toggle source
# File lib/convertator/converter.rb, line 21
def add(middleware)
  middleware.prev = @chain.last
  @chain << middleware
end
convert(amount, currency_from, currency_to) click to toggle source
# File lib/convertator/converter.rb, line 41
def convert(amount, currency_from, currency_to)
  round(amount * ratio(currency_from, currency_to))
end
convert_multi(amount, currency_from, currencies_to) click to toggle source
# File lib/convertator/converter.rb, line 49
def convert_multi(amount, currency_from, currencies_to)
  currencies_to.map do |currency_to|
    convert(amount, currency_from, currency_to)
  end
end
convert_multi_s(amount, currency_from, currencies_to) click to toggle source
# File lib/convertator/converter.rb, line 55
def convert_multi_s(amount, currency_from, currencies_to)
  currencies_to.map do |currency_to|
    convert_s(amount, currency_from, currency_to)
  end
end
convert_s(amount, currency_from, currency_to) click to toggle source
# File lib/convertator/converter.rb, line 45
def convert_s(amount, currency_from, currency_to)
  convert(amount, currency_from, currency_to).to_digits
end
rate(currency) click to toggle source
# File lib/convertator/converter.rb, line 30
def rate(currency)
  currency = normalize_currency(currency)
  rate = rates[currency]
  raise UnknownCurrencyError, "Unknown currency #{currency}" unless rate
  round(BigDecimal.new(rate, @accuracy))
end
rates() click to toggle source
# File lib/convertator/converter.rb, line 26
def rates
  symbolize_keys(@chain.last.call)
end
ratio(currency_from, currency_to) click to toggle source
# File lib/convertator/converter.rb, line 37
def ratio(currency_from, currency_to)
  round(rate(currency_from) / rate(currency_to))
end

Private Instance Methods

load_provider(name) click to toggle source
# File lib/convertator/converter.rb, line 70
def load_provider(name)
  try_require(name)
  klass = Object.const_get(
    "Convertator::Providers::#{name.capitalize}Provider"
  )
  klass.new
end
round(value) click to toggle source
# File lib/convertator/converter.rb, line 63
def round(value)
  BigDecimal.save_rounding_mode do
    BigDecimal.mode(BigDecimal::ROUND_MODE, :half_up)
    value.round(@accuracy)
  end
end
try_require(name) click to toggle source
# File lib/convertator/converter.rb, line 78
def try_require(name)
  require ::File.join(
    __dir__,
    'providers',
    "#{name.downcase}_provider"
  )
end