module FxFetcher::ClassMethods

Public Instance Methods

at(date, base, counter) click to toggle source
# File lib/fx_fetcher.rb, line 9
def at(date, base, counter)
  if currencies_present_for_date(date)
    search_for_rate(date, base, counter)
  else
    "No rates available for this date"
  end
end
currencies() click to toggle source

helper to create list of available currencies to use in form

# File lib/fx_fetcher.rb, line 18
def currencies
  currencies = []
  rates_for_date = self.where(rate_date: self.first.rate_date)
  rates_for_date.each { |rate| currencies << rate.counter_currency }
  currencies << rates_for_date.first.base_currency
end
valid_amount?(amount) click to toggle source

helper to check if value is non text and greater than zero

# File lib/fx_fetcher.rb, line 26
def valid_amount?(amount)
  amount.to_f > 0.0
end

Private Instance Methods

check_if_valid(pair_1, pair_2) click to toggle source
# File lib/fx_fetcher.rb, line 53
def check_if_valid(pair_1, pair_2)
  if pair_1.present? && pair_2.present?
    (1/pair_1.rate * pair_2.rate).round(4)
  else
    "No rate available for this conversion"
  end
end
currencies_present_for_date(date) click to toggle source
# File lib/fx_fetcher.rb, line 32
def currencies_present_for_date(date)
  date == "" ? date = nil : date
  self.where(rate_date: date).present?
end
perform_cross_rate_calculation(rates_for_date, base, counter) click to toggle source
# File lib/fx_fetcher.rb, line 47
def perform_cross_rate_calculation(rates_for_date, base, counter)
  pair_1 = rates_for_date.find { |rate| rate.counter_currency == base }
  pair_2 = rates_for_date.find { |rate| rate.counter_currency == counter }
  check_if_valid(pair_1, pair_2)
end
search_for_rate(date, base, counter) click to toggle source
# File lib/fx_fetcher.rb, line 37
def search_for_rate(date, base, counter)
  rates_for_date = self.where(rate_date: date)
  exchange_rate = rates_for_date.each do |rate|
    return 1 if base == counter
    return rate.rate if rate.base_currency == base && rate.counter_currency == counter
    return (1/rate.rate).round(4) if rate.base_currency == counter && rate.counter_currency == base
  end
  perform_cross_rate_calculation(rates_for_date, base, counter)
end