2024-02-10 16:18:56 -06:00
|
|
|
class ExchangeRate < ApplicationRecord
|
2024-03-27 09:16:00 -06:00
|
|
|
include Provided
|
|
|
|
|
2024-07-08 09:04:59 -04:00
|
|
|
validates :from_currency, :to_currency, :date, :rate, presence: true
|
2024-03-15 12:21:59 -07:00
|
|
|
|
2024-03-21 13:39:10 -04:00
|
|
|
class << self
|
2024-07-08 09:04:59 -04:00
|
|
|
def find_rate(from:, to:, date:, cache: true)
|
|
|
|
result = find_by \
|
|
|
|
from_currency: from,
|
|
|
|
to_currency: to,
|
2024-03-27 09:16:00 -06:00
|
|
|
date: date
|
2024-02-26 20:20:38 +05:30
|
|
|
|
2024-07-08 09:04:59 -04:00
|
|
|
result || fetch_rate_from_provider(from:, to:, date:, cache:)
|
2024-03-21 13:39:10 -04:00
|
|
|
end
|
2024-03-07 17:46:36 -05:00
|
|
|
|
2024-07-08 09:04:59 -04:00
|
|
|
def find_rates(from:, to:, start_date:, end_date: Date.current, cache: true)
|
|
|
|
rates = self.where(from_currency: from, to_currency: to, date: start_date..end_date).to_a
|
2024-08-09 16:57:33 +02:00
|
|
|
all_dates = (start_date..end_date).to_a
|
|
|
|
existing_dates = rates.map(&:date)
|
2024-07-08 09:04:59 -04:00
|
|
|
missing_dates = all_dates - existing_dates
|
|
|
|
if missing_dates.any?
|
2024-08-09 16:57:33 +02:00
|
|
|
rates += fetch_rates_from_provider(from:, to:, start_date: missing_dates.first, end_date: missing_dates.last, cache:)
|
2024-07-08 09:04:59 -04:00
|
|
|
end
|
2024-05-16 21:57:21 +02:00
|
|
|
|
2024-07-08 09:04:59 -04:00
|
|
|
rates
|
2024-05-16 21:57:21 +02:00
|
|
|
end
|
2024-02-10 16:18:56 -06:00
|
|
|
end
|
|
|
|
end
|