Sha256: f0c2f4a1f276396d7ff9a6a2d3af71fb4fd019de3642083d13a06d0708a44762

Contents?: true

Size: 1.17 KB

Versions: 18

Compression:

Stored size: 1.17 KB

Contents

class TimedCache
  class Value < Struct.new(:value, :timestamp)
    def self.json_create(hash)
      new(*hash.values_at('value', 'timestamp'))
    end

    def as_json(*)
      super | { JSON.create_id => self.class.name }
    end
  end

  def initialize(name, ttl: 60, jitter: 1..5, &block)
    @name   = name
    @ttl    = ttl
    @jitter = jitter
    block or raise ArgumentError, 'block is required'
    @block = block
    @redis = Redis.new # RedisPool::Pool.connection(:timed_cache, configuration: :redis)
  end

  def namespaced(key)
    "timed_cache:#{key}"
  end

  def value
    now = Time.now
    if stored = stored_value
      if (now - @ttl).to_i >= stored.timestamp
        Thread.new {
          sleep @jitter
          if stored_value.timestamp <= stored.timestamp
            @redis.set namespaced(@name), new_value(now).to_json
          end
        }
      end
      stored.value
    else
      nv = new_value(now)
      @redis.set namespaced(@name), nv.to_json
      nv.value
    end
  end

  def new_value(now)
    Value.new(@block.(), now.to_i)
  end

  def stored_value
    @redis.get(namespaced(@name)).full? { |s| ::JSON.parse(s, create_additions: true) rescue nil }
  end
end

Version data entries

18 entries across 15 versions & 2 rubygems

Version Path
tins-1.33.0 lib/tins/timed_cache.rb
tdiary-5.2.4 vendor/bundle/ruby/3.1.0/gems/tins-1.31.1/lib/tins/timed_cache.rb
tins-1.32.1 lib/tins/timed_cache.rb
tins-1.32.0 lib/tins/timed_cache.rb
tdiary-5.2.3 vendor/bundle/ruby/3.1.0/gems/tins-1.31.1/lib/tins/timed_cache.rb
tdiary-5.2.2 vendor/bundle/ruby/3.1.0/gems/tins-1.31.1/lib/tins/timed_cache.rb
tins-1.31.1 lib/tins/timed_cache.rb
tdiary-5.2.1 vendor/bundle/ruby/3.1.0/gems/tins-1.31.0/lib/tins/timed_cache.rb
tins-1.31.0 lib/tins/timed_cache.rb
tins-1.30.0 lib/tins/timed_cache.rb
tdiary-5.2.0 vendor/bundle/ruby/2.7.0/gems/tins-1.29.1/lib/tins/timed_cache.rb
tdiary-5.2.0 vendor/bundle/ruby/3.0.0/gems/tins-1.29.1/lib/tins/timed_cache.rb
tdiary-5.1.7 vendor/bundle/ruby/2.7.0/gems/tins-1.29.1/lib/tins/timed_cache.rb
tdiary-5.1.7 vendor/bundle/ruby/3.0.0/gems/tins-1.29.1/lib/tins/timed_cache.rb
tdiary-5.1.6 vendor/bundle/ruby/3.0.0/gems/tins-1.29.1/lib/tins/timed_cache.rb
tdiary-5.1.6 vendor/bundle/ruby/2.7.0/gems/tins-1.29.1/lib/tins/timed_cache.rb
tins-1.29.1 lib/tins/timed_cache.rb
tins-1.29.0 lib/tins/timed_cache.rb