Files
sure/app/models/exchange_rate/provided.rb
Vincent Teo 5bdefe6e63 feat: Add Twelve Data provider for exchange rates and securities (#2)
* feat: Add Twelve Data provider for exchange rates and securities

* test: fix hosting controller test, linting

* fix: add countries gem to handle country codes in Twelve Data provider

* fix: allow security search combobox to have no logo

* refactor: update Twelve Data provider use time series endpoint

* fix: set twelve data as default provider
2025-07-31 23:31:37 +02:00

49 lines
1.4 KiB
Ruby

module ExchangeRate::Provided
extend ActiveSupport::Concern
class_methods do
def provider
provider = ENV["EXCHANGE_RATE_PROVIDER"] || "twelve_data"
registry = Provider::Registry.for_concept(:exchange_rates)
registry.get_provider(provider.to_sym)
end
def find_or_fetch_rate(from:, to:, date: Date.current, cache: true)
rate = find_by(from_currency: from, to_currency: to, date: date)
return rate if rate.present?
return nil unless provider.present? # No provider configured (some self-hosted apps)
response = provider.fetch_exchange_rate(from: from, to: to, date: date)
return nil unless response.success? # Provider error
rate = response.data
ExchangeRate.find_or_create_by!(
from_currency: rate.from,
to_currency: rate.to,
date: rate.date,
rate: rate.rate
) if cache
rate
end
# @return [Integer] The number of exchange rates synced
def import_provider_rates(from:, to:, start_date:, end_date:, clear_cache: false)
unless provider.present?
Rails.logger.warn("No provider configured for ExchangeRate.import_provider_rates")
return 0
end
ExchangeRate::Importer.new(
exchange_rate_provider: provider,
from: from,
to: to,
start_date: start_date,
end_date: end_date,
clear_cache: clear_cache
).import_provider_rates
end
end
end