Class: LocalCacheStore
- Inherits:
-
Object
- Object
- LocalCacheStore
- Defined in:
- lib/cache_store.rb
Overview
Implements a local in-memory cache store.
Instance Method Summary collapse
-
#exist?(key) ⇒ Boolean
Checks if a value exists within this cache store for a specific key.
-
#get(key, expires_in = 0) ⇒ Object
Gets a value from this cache store by its unique key.
-
#initialize(_namespace = nil) ⇒ LocalCacheStore
constructor
A new instance of LocalCacheStore.
-
#remove(key) ⇒ Object
Removes a value from this cache store by its unique key.
-
#set(key, value, expires_in = 0) ⇒ Object
Stores a value in this cache store by its key.
Constructor Details
#initialize(_namespace = nil) ⇒ LocalCacheStore
43 44 45 |
# File 'lib/cache_store.rb', line 43 def initialize(_namespace = nil) @store = {} end |
Instance Method Details
#exist?(key) ⇒ Boolean
Checks if a value exists within this cache store for a specific key.
97 98 99 |
# File 'lib/cache_store.rb', line 97 def exist?(key) @store.key? key end |
#get(key, expires_in = 0) ⇒ Object
Gets a value from this cache store by its unique key.
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/cache_store.rb', line 64 def get(key, expires_in = 0) item = @store[key] if item if item[:expires] && item[:expires] < Time.now # An expired entry has been found if block_given? value = yield set(key, value, expires_in) return value else remove(key) return nil end else # An item was found which has not expired return item[:value] end elsif block_given? value = yield set(key, value, expires_in) return value end end |
#remove(key) ⇒ Object
Removes a value from this cache store by its unique key.
89 90 91 |
# File 'lib/cache_store.rb', line 89 def remove(key) @store.delete key end |
#set(key, value, expires_in = 0) ⇒ Object
Stores a value in this cache store by its key.
52 53 54 55 56 57 |
# File 'lib/cache_store.rb', line 52 def set(key, value, expires_in = 0) if expires_in > 0 expires = Time.now + expires_in end @store.store(key, {value: value, expires: expires}) end |