我花了几天时间搜索整个互联网,但找不到任何实现。因此,我实施了一个并愿意分享。
问问题
7 次
1 回答
0
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
于 2022-03-02T14:40:17.030 回答