|
| 1 | +require 'bigdecimal' |
| 2 | +require 'money/distributed/redis' |
| 3 | + |
| 4 | +class Money |
| 5 | + module Distributed |
| 6 | + # Storage for `Money::Bank::VariableExchange` that stores rates in Redis |
| 7 | + class Storage |
| 8 | + INDEX_KEY_SEPARATOR = '_TO_'.freeze |
| 9 | + REDIS_KEY = 'money_rates'.freeze |
| 10 | + |
| 11 | + def initialize(redis, cache_ttl = nil) |
| 12 | + @redis = Money::Distributed::Redis.new(redis) |
| 13 | + |
| 14 | + @cache = {} |
| 15 | + @cache_ttl = cache_ttl |
| 16 | + @cache_updated_at = nil |
| 17 | + |
| 18 | + @mutex = Mutex.new |
| 19 | + end |
| 20 | + |
| 21 | + def add_rate(iso_from, iso_to, rate) |
| 22 | + @redis.exec do |r| |
| 23 | + r.hset(REDIS_KEY, key_for(iso_from, iso_to), rate) |
| 24 | + end |
| 25 | + clear_cache |
| 26 | + end |
| 27 | + |
| 28 | + def get_rate(iso_from, iso_to) |
| 29 | + cached_rates[key_for(iso_from, iso_to)] |
| 30 | + end |
| 31 | + |
| 32 | + def each_rate |
| 33 | + enum = Enumerator.new do |yielder| |
| 34 | + cached_rates.each do |key, rate| |
| 35 | + iso_from, iso_to = key.split(INDEX_KEY_SEPARATOR) |
| 36 | + yielder.yield iso_from, iso_to, rate |
| 37 | + end |
| 38 | + end |
| 39 | + |
| 40 | + block_given? ? enum.each(&block) : enum |
| 41 | + end |
| 42 | + |
| 43 | + def transaction |
| 44 | + # We don't need transactions, we all thread safe here |
| 45 | + yield |
| 46 | + end |
| 47 | + |
| 48 | + def marshal_dump |
| 49 | + [self.class, @cache_ttl] |
| 50 | + end |
| 51 | + |
| 52 | + private |
| 53 | + |
| 54 | + def key_for(iso_from, iso_to) |
| 55 | + [iso_from, iso_to].join(INDEX_KEY_SEPARATOR).upcase |
| 56 | + end |
| 57 | + |
| 58 | + def cached_rates |
| 59 | + @mutex.synchronize do |
| 60 | + retrieve_rates if @cache.empty? || cache_outdated? |
| 61 | + @cache |
| 62 | + end |
| 63 | + end |
| 64 | + |
| 65 | + def cache_outdated? |
| 66 | + return false unless @cache_ttl |
| 67 | + @cache_updated_at.nil? || |
| 68 | + @cache_updated_at < Time.now - @cache_ttl |
| 69 | + end |
| 70 | + |
| 71 | + def clear_cache |
| 72 | + @mutex.synchronize do |
| 73 | + @cache.clear |
| 74 | + end |
| 75 | + end |
| 76 | + |
| 77 | + def retrieve_rates |
| 78 | + @redis.exec do |r| |
| 79 | + r.hgetall(REDIS_KEY).each_with_object(@cache) do |(key, val), h| |
| 80 | + h[key] = BigDecimal.new(val) |
| 81 | + end |
| 82 | + end |
| 83 | + @cache_updated_at = Time.now |
| 84 | + end |
| 85 | + end |
| 86 | + end |
| 87 | +end |
0 commit comments