Class: TocDoc::Cache::MemoryStore
- Inherits:
-
Object
- Object
- TocDoc::Cache::MemoryStore
- Defined in:
- lib/toc_doc/cache/memory_store.rb
Overview
A thread-safe, in-memory response cache with per-entry TTL.
Uses lazy expiration: expired entries are evicted on #read, not via a
background sweep. The key space is bounded by the number of distinct API
URLs, so the overhead is negligible for typical gem usage.
Compatible with the ActiveSupport::Cache::Store interface for the methods
it implements (+read+, write, delete, clear).
Instance Method Summary collapse
-
#clear
Removes all entries from the store.
-
#delete(key)
Deletes the entry for
key. -
#initialize(default_ttl: 300) ⇒ MemoryStore
constructor
A new instance of MemoryStore.
-
#read(key) ⇒ Object?
Reads the value stored under
key. -
#write(key, value, expires_in: @default_ttl) ⇒ Object
Stores
valueunderkeywith the given TTL.
Constructor Details
#initialize(default_ttl: 300) ⇒ MemoryStore
Returns a new instance of MemoryStore.
22 23 24 25 26 |
# File 'lib/toc_doc/cache/memory_store.rb', line 22 def initialize(default_ttl: 300) @default_ttl = default_ttl @store = {} @monitor = Monitor.new end |
Instance Method Details
#clear
This method returns an undefined value.
Removes all entries from the store.
76 77 78 |
# File 'lib/toc_doc/cache/memory_store.rb', line 76 def clear @monitor.synchronize { @store.clear } end |
#delete(key)
This method returns an undefined value.
Deletes the entry for key.
69 70 71 |
# File 'lib/toc_doc/cache/memory_store.rb', line 69 def delete(key) @monitor.synchronize { @store.delete(key) } end |
#read(key) ⇒ Object?
Reads the value stored under key.
Returns nil when the key is absent or has expired (and evicts the
entry in the latter case).
35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/toc_doc/cache/memory_store.rb', line 35 def read(key) @monitor.synchronize do entry = @store[key] return nil unless entry if Process.clock_gettime(Process::CLOCK_MONOTONIC) > entry[:expires_at] @store.delete(key) return nil end entry[:value] end end |
#write(key, value, expires_in: @default_ttl) ⇒ Object
Stores value under key with the given TTL.
55 56 57 58 59 60 61 62 63 |
# File 'lib/toc_doc/cache/memory_store.rb', line 55 def write(key, value, expires_in: @default_ttl) @monitor.synchronize do @store[key] = { value: value, expires_at: Process.clock_gettime(Process::CLOCK_MONOTONIC) + expires_in } value end end |