首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何实现Redis货币商店/开放-汇率-银行Rails

如何实现Redis货币商店/开放-汇率-银行Rails
EN

Stack Overflow用户
提问于 2022-03-02 14:40:17
回答 1查看 128关注 0票数 1

我花了几天时间在整个互联网上搜索,却找不到任何实现。因此,我执行了一项建议,并希望与大家分享。

EN

回答 1

Stack Overflow用户

发布于 2022-03-02 14:40:17

代码语言:javascript
复制
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
代码语言:javascript
复制
# 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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71324532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档