Class: TimedCache
Defined Under Namespace
Classes: Value
Instance Method Summary collapse
-
#initialize(name, ttl: 60, jitter: 1..5, &block) ⇒ TimedCache
constructor
A new instance of TimedCache.
- #namespaced(key) ⇒ Object
- #new_value(now) ⇒ Object
- #stored_value ⇒ Object
- #value ⇒ Object
Constructor Details
#initialize(name, ttl: 60, jitter: 1..5, &block) ⇒ TimedCache
Returns a new instance of TimedCache.
12 13 14 15 16 17 18 19 |
# File 'lib/tins/timed_cache.rb', line 12 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 end |
Instance Method Details
#namespaced(key) ⇒ Object
21 22 23 |
# File 'lib/tins/timed_cache.rb', line 21 def namespaced(key) "timed_cache:#{key}" end |
#new_value(now) ⇒ Object
44 45 46 |
# File 'lib/tins/timed_cache.rb', line 44 def new_value(now) Value.new(@block.(), now.to_i) end |
#stored_value ⇒ Object
48 49 50 |
# File 'lib/tins/timed_cache.rb', line 48 def stored_value @redis.get(namespaced(@name)).full? { |s| ::JSON.parse(s, create_additions: true) rescue nil } end |
#value ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/tins/timed_cache.rb', line 25 def value now = Time.now if stored = stored_value if (now - @ttl).to_i >= stored. Thread.new { sleep @jitter if stored_value. <= stored. @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 |