1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-07-24 15:49:39 +02:00
Maybe/app/models/exchange_rate/provided.rb
Tony Vincent 6fa40e0fa2
Fetch exchange rates in bulk from synth (#1069)
* Fetch exchnage rates in bulk

* Handle paginated response

* Rename method and improve tests

* Change argument names

* Use standard date format
2024-08-09 10:57:33 -04:00

58 lines
1.4 KiB
Ruby

module ExchangeRate::Provided
extend ActiveSupport::Concern
include Providable
class_methods do
private
def fetch_rates_from_provider(from:, to:, start_date:, end_date: Date.current, cache: false)
return [] unless exchange_rates_provider.present?
response = exchange_rates_provider.fetch_exchange_rates \
from: from,
to: to,
start_date: start_date,
end_date: end_date
if response.success?
response.rates.map do |exchange_rate|
rate = ExchangeRate.new \
from_currency: from,
to_currency: to,
date: exchange_rate.dig(:date).to_date,
rate: exchange_rate.dig(:rate)
rate.save! if cache
rate
rescue ActiveRecord::RecordNotUnique
next
end
else
[]
end
end
def fetch_rate_from_provider(from:, to:, date:, cache: false)
return nil unless exchange_rates_provider.present?
response = exchange_rates_provider.fetch_exchange_rate \
from: from,
to: to,
date: date
if response.success?
rate = ExchangeRate.new \
from_currency: from,
to_currency: to,
rate: response.rate,
date: date
rate.save! if cache
rate
else
nil
end
end
end
end