2024-02-10 16:18:56 -06:00
|
|
|
class ExchangeRate < ApplicationRecord
|
2024-03-27 09:16:00 -06:00
|
|
|
include Provided
|
|
|
|
|
2024-03-15 12:21:59 -07:00
|
|
|
validates :base_currency, :converted_currency, presence: true
|
|
|
|
|
2024-03-21 13:39:10 -04:00
|
|
|
class << self
|
2024-03-27 09:16:00 -06:00
|
|
|
def find_rate(from:, to:, date:)
|
|
|
|
find_by \
|
|
|
|
base_currency: Money::Currency.new(from).iso_code,
|
|
|
|
converted_currency: Money::Currency.new(to).iso_code,
|
|
|
|
date: date
|
2024-03-21 13:39:10 -04:00
|
|
|
end
|
2024-02-26 20:20:38 +05:30
|
|
|
|
2024-03-27 09:16:00 -06:00
|
|
|
def find_rate_or_fetch(from:, to:, date:)
|
2024-05-27 18:10:28 +02:00
|
|
|
find_rate(from:, to:, date:) || fetch_rate_from_provider(from:, to:, date:)&.tap(&:save!)
|
2024-03-21 13:39:10 -04:00
|
|
|
end
|
2024-03-07 17:46:36 -05:00
|
|
|
|
2024-05-27 18:10:28 +02:00
|
|
|
def get_rates(from, to, dates)
|
|
|
|
where(base_currency: from, converted_currency: to, date: dates).order(:date)
|
2024-03-21 13:39:10 -04:00
|
|
|
end
|
2024-05-16 21:57:21 +02:00
|
|
|
|
|
|
|
def convert(value:, from:, to:, date:)
|
|
|
|
rate = ExchangeRate.find_by(base_currency: from, converted_currency: to, date:)
|
|
|
|
raise "Conversion from: #{from} to: #{to} on: #{date} not found" unless rate
|
|
|
|
|
|
|
|
value * rate.rate
|
|
|
|
end
|
2024-02-10 16:18:56 -06:00
|
|
|
end
|
|
|
|
end
|