2024-03-27 09:16:00 -06:00
|
|
|
module ExchangeRate::Provided
|
|
|
|
extend ActiveSupport::Concern
|
2024-07-08 09:04:59 -04:00
|
|
|
|
2024-03-27 09:16:00 -06:00
|
|
|
include Providable
|
|
|
|
|
|
|
|
class_methods do
|
|
|
|
private
|
2024-07-08 09:04:59 -04:00
|
|
|
|
|
|
|
def fetch_rates_from_provider(from:, to:, dates:, cache: false)
|
|
|
|
return [] unless exchange_rates_provider.present?
|
|
|
|
|
|
|
|
dates.map do |date|
|
|
|
|
fetch_rate_from_provider from:, to:, date:, cache:
|
|
|
|
end.compact
|
|
|
|
end
|
|
|
|
|
|
|
|
def fetch_rate_from_provider(from:, to:, date:, cache: false)
|
|
|
|
return nil unless exchange_rates_provider.present?
|
2024-05-27 18:10:28 +02:00
|
|
|
|
2024-03-27 09:16:00 -06:00
|
|
|
response = exchange_rates_provider.fetch_exchange_rate \
|
2024-07-08 09:04:59 -04:00
|
|
|
from: from,
|
|
|
|
to: to,
|
2024-03-27 09:16:00 -06:00
|
|
|
date: date
|
|
|
|
|
|
|
|
if response.success?
|
2024-07-08 09:04:59 -04:00
|
|
|
rate = ExchangeRate.new \
|
|
|
|
from_currency: from,
|
|
|
|
to_currency: to,
|
2024-03-27 09:16:00 -06:00
|
|
|
rate: response.rate,
|
|
|
|
date: date
|
2024-07-08 09:04:59 -04:00
|
|
|
|
|
|
|
rate.save! if cache
|
|
|
|
rate
|
2024-03-27 09:16:00 -06:00
|
|
|
else
|
2024-07-08 09:04:59 -04:00
|
|
|
nil
|
2024-03-27 09:16:00 -06:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|