Class: Whoosh::Cache::MemoryStore
- Inherits:
-
Object
- Object
- Whoosh::Cache::MemoryStore
- Defined in:
- lib/whoosh/cache/memory_store.rb
Instance Method Summary collapse
- #clear ⇒ Object
- #close ⇒ Object
- #delete(key) ⇒ Object
- #fetch(key, ttl: nil) ⇒ Object
- #get(key) ⇒ Object
-
#initialize(default_ttl: 300) ⇒ MemoryStore
constructor
A new instance of MemoryStore.
- #set(key, value, ttl: nil) ⇒ Object
Constructor Details
#initialize(default_ttl: 300) ⇒ MemoryStore
Returns a new instance of MemoryStore.
7 8 9 10 11 |
# File 'lib/whoosh/cache/memory_store.rb', line 7 def initialize(default_ttl: 300) @store = {} @default_ttl = default_ttl @mutex = Mutex.new end |
Instance Method Details
#clear ⇒ Object
47 48 49 50 |
# File 'lib/whoosh/cache/memory_store.rb', line 47 def clear @mutex.synchronize { @store.clear } true end |
#close ⇒ Object
52 53 54 |
# File 'lib/whoosh/cache/memory_store.rb', line 52 def close # No-op end |
#delete(key) ⇒ Object
42 43 44 45 |
# File 'lib/whoosh/cache/memory_store.rb', line 42 def delete(key) @mutex.synchronize { @store.delete(key) } true end |
#fetch(key, ttl: nil) ⇒ Object
34 35 36 37 38 39 40 |
# File 'lib/whoosh/cache/memory_store.rb', line 34 def fetch(key, ttl: nil) existing = get(key) return existing unless existing.nil? value = yield set(key, value, ttl: ttl) Serialization::Json.decode(Serialization::Json.encode(value)) end |
#get(key) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/whoosh/cache/memory_store.rb', line 13 def get(key) @mutex.synchronize do entry = @store[key] return nil unless entry if entry[:expires_at] && Time.now.to_f > entry[:expires_at] @store.delete(key) return nil end entry[:value] end end |
#set(key, value, ttl: nil) ⇒ Object
25 26 27 28 29 30 31 32 |
# File 'lib/whoosh/cache/memory_store.rb', line 25 def set(key, value, ttl: nil) ttl ||= @default_ttl serialized = Serialization::Json.decode(Serialization::Json.encode(value)) @mutex.synchronize do @store[key] = { value: serialized, expires_at: Time.now.to_f + ttl } end true end |