Created
May 29, 2024 11:07
-
-
Save deekshithh/87cce59396e8fdcc2e5b0f4039b2852a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Helper::CurrencyConverter | |
CACHE_EXPIRY = 1.minute | |
def initialize(base_currency, target_currency, api_client = OpenExchangeRates::Rates.new) | |
@base_currency = base_currency | |
@target_currency = target_currency | |
@api_client = api_client | |
end | |
# Converts the specified amount from the base currency to the target currency. | |
# Returns the converted amount rounded to 2 decimal places. | |
def convert(amount) | |
rate = get_rate | |
(amount * rate).round(2) if rate | |
end | |
private | |
# Retrieves the exchange rate for the specified target currency. | |
# Caches the result for CACHE_EXPIRY duration. | |
# If an error occurs, logs the error and notifies via Slack. | |
def get_rate | |
Rails.cache.fetch(rate_cache_key(@target_currency), expires_in: CACHE_EXPIRY) do | |
Rails.logger.info("Fetching exchange rate for #{@base_currency} to #{@target_currency}") | |
begin | |
@api_client.exchange_rate(from: @base_currency, to: @target_currency) | |
rescue StandardError => e | |
Rails.logger.error("Could not retrieve currency conversion data from Open Exchange Rates API: #{e}") | |
notify_error(e) | |
nil | |
end | |
end | |
end | |
# Generates a cache key for the exchange rate between the base currency and the target currency. | |
def rate_cache_key | |
"rate_#{@base_currency}_#{@target_currency}" | |
end | |
# Notifies the Slack channel about the currency conversion error. | |
def notify_error(error) | |
Notification::Slack.new.send_conversion_errors(error) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment