'How to implement a Redis Store for Money/Open-Exchange-Rate-Bank Ruby on Rails
I spent days searching the whole internet and couldn't find any implementation. I, therefore, implemented one and will like to share.
Solution 1:[1]
class RedisRateStore
INDEX_KEY_SEPARATOR = '_TO_'.freeze
# Using second db of the redis instance
# because sidekiq uses the first db
REDIS_DATABASE = 1
# Using Hash to store rates data
REDIS_STORE_KEY = 'rates'
def initialize
conn_url = "#{Rails.application.credentials.redis_server}/#{REDIS_DATABASE}"
@connection = Redis.new(url: conn_url)
end
def add_rate(iso_from, iso_to, rate)
@connection.hset(REDIS_STORE_KEY, rate_key_for(iso_from, iso_to), rate)
end
def get_rate(iso_from, iso_to)
@connection.hget(REDIS_STORE_KEY, rate_key_for(iso_from, iso_to))
end
def each_rate
rates = @connection.hgetall(REDIS_STORE_KEY)
return to_enum(:each_rate) unless block_given?
rates.each do |key, rate|
iso_from, iso_to = key.split(INDEX_KEY_SEPARATOR)
yield iso_from, iso_to, rate
end
end
def transaction
yield
end
private
def rate_key_for(iso_from, iso_to)
[iso_from, iso_to].join(INDEX_KEY_SEPARATOR).upcase
end
end
# config/initializers/open-exchange-rate.rb
# frozen_string_literal: true
require 'money/bank/open_exchange_rates_bank'
Rails.application.config.to_prepare do
oxr = Money::Bank::OpenExchangeRatesBank.new(RedisRateStore.new)
oxr.app_id = Rails.application.credentials.oxr_app_id
oxr.cache = 'db/rates.json'
oxr.ttl_in_seconds = 3600
oxr.prettyprint = false
Money.default_bank = oxr
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kofi Asare |
