Class: Printavo::MemoryStore
- Inherits:
-
Object
- Object
- Printavo::MemoryStore
- Defined in:
- lib/printavo/memory_store.rb
Overview
A simple thread-safe in-memory cache store for use without Rails or Redis.
Implements the same fetch / delete interface as Rails.cache, so it
can be swapped for any compatible store without changing call sites.
Instance Method Summary collapse
-
#delete(key) ⇒ nil
Removes
keyfrom the cache. -
#fetch(key, expires_in: nil) ⇒ Object
Returns the cached value for
key, or calls the block, stores the result, and returns it. -
#initialize ⇒ MemoryStore
constructor
A new instance of MemoryStore.
Constructor Details
#initialize ⇒ MemoryStore
Returns a new instance of MemoryStore.
24 25 26 27 28 |
# File 'lib/printavo/memory_store.rb', line 24 def initialize @store = {} @expires_at = {} @mutex = Mutex.new end |
Instance Method Details
#delete(key) ⇒ nil
Removes key from the cache.
50 51 52 53 54 55 56 |
# File 'lib/printavo/memory_store.rb', line 50 def delete(key) @mutex.synchronize do @store.delete(key) @expires_at.delete(key) end nil end |
#fetch(key, expires_in: nil) ⇒ Object
Returns the cached value for key, or calls the block, stores the
result, and returns it. Expired entries are treated as missing.
37 38 39 40 41 42 43 44 |
# File 'lib/printavo/memory_store.rb', line 37 def fetch(key, expires_in: nil) @mutex.synchronize do cached = read(key) return cached unless cached.nil? yield.tap { |v| write(key, v, expires_in: expires_in) } end end |