Class: CardDB::MemoryCache
- Inherits:
-
Object
- Object
- CardDB::MemoryCache
- Defined in:
- lib/carddb/cache.rb
Overview
Simple in-memory cache with TTL support. Compatible with Rails.cache interface (read/write/delete).
Instance Method Summary collapse
-
#clear ⇒ void
Clear all cached values.
-
#delete(key) ⇒ Boolean
Delete a value from the cache.
-
#exist?(key) ⇒ Boolean
Check if a key exists and is not expired.
-
#initialize ⇒ MemoryCache
constructor
A new instance of MemoryCache.
-
#read(key) ⇒ Object?
Read a value from the cache.
-
#size ⇒ Integer
Get the number of cached entries (for debugging).
-
#write(key, value, expires_in: nil) ⇒ Object
Write a value to the cache.
Constructor Details
#initialize ⇒ MemoryCache
Returns a new instance of MemoryCache.
14 15 16 17 |
# File 'lib/carddb/cache.rb', line 14 def initialize @store = {} @mutex = Mutex.new end |
Instance Method Details
#clear ⇒ void
This method returns an undefined value.
Clear all cached values.
72 73 74 75 76 |
# File 'lib/carddb/cache.rb', line 72 def clear @mutex.synchronize do @store.clear end end |
#delete(key) ⇒ Boolean
Delete a value from the cache.
55 56 57 58 59 |
# File 'lib/carddb/cache.rb', line 55 def delete(key) @mutex.synchronize do !!@store.delete(key) end end |
#exist?(key) ⇒ Boolean
Check if a key exists and is not expired.
65 66 67 |
# File 'lib/carddb/cache.rb', line 65 def exist?(key) !read(key).nil? end |
#read(key) ⇒ Object?
Read a value from the cache.
23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/carddb/cache.rb', line 23 def read(key) @mutex.synchronize do entry = @store[key] return nil unless entry if entry[:expires_at] && Time.now > entry[:expires_at] @store.delete(key) return nil end entry[:value] end end |
#size ⇒ Integer
Get the number of cached entries (for debugging).
81 82 83 84 85 86 87 88 |
# File 'lib/carddb/cache.rb', line 81 def size @mutex.synchronize do # Clean up expired entries first now = Time.now @store.delete_if { |_, entry| entry[:expires_at] && now > entry[:expires_at] } @store.size end end |
#write(key, value, expires_in: nil) ⇒ Object
Write a value to the cache.
43 44 45 46 47 48 49 |
# File 'lib/carddb/cache.rb', line 43 def write(key, value, expires_in: nil) @mutex.synchronize do expires_at = expires_in ? Time.now + expires_in : nil @store[key] = { value: value, expires_at: expires_at } value end end |