Class: RSX::Cache::Memory
- Inherits:
-
Object
- Object
- RSX::Cache::Memory
- Defined in:
- lib/rsx/cache.rb
Overview
Thread-safe in-process LRU. This is the default store so caching works with no configuration and no dependencies.
Constant Summary collapse
- DEFAULT_MAX_ENTRIES =
4096
Instance Method Summary collapse
- #clear ⇒ Object
- #delete(key) ⇒ Object
- #fetch(key, expires_in: nil) ⇒ Object
-
#initialize(max_entries: DEFAULT_MAX_ENTRIES) ⇒ Memory
constructor
A new instance of Memory.
- #read(key) ⇒ Object
- #size ⇒ Object
- #write(key, value, expires_in: nil) ⇒ Object
Constructor Details
#initialize(max_entries: DEFAULT_MAX_ENTRIES) ⇒ Memory
Returns a new instance of Memory.
13 14 15 16 17 |
# File 'lib/rsx/cache.rb', line 13 def initialize(max_entries: DEFAULT_MAX_ENTRIES) @max_entries = max_entries @entries = {} @lock = Mutex.new end |
Instance Method Details
#clear ⇒ Object
56 57 58 59 |
# File 'lib/rsx/cache.rb', line 56 def clear @lock.synchronize { @entries.clear } self end |
#delete(key) ⇒ Object
52 53 54 |
# File 'lib/rsx/cache.rb', line 52 def delete(key) @lock.synchronize { @entries.delete(key) } end |
#fetch(key, expires_in: nil) ⇒ Object
19 20 21 22 23 24 |
# File 'lib/rsx/cache.rb', line 19 def fetch(key, expires_in: nil) found = read(key) return found unless found.nil? write(key, yield, expires_in: expires_in) end |
#read(key) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/rsx/cache.rb', line 26 def read(key) @lock.synchronize do value, expires_at = @entries[key] next nil if value.nil? if expires_at && expires_at < now @entries.delete(key) next nil end # Re-insert so the entry counts as most recently used. @entries.delete(key) @entries[key] = [value, expires_at] value end end |
#size ⇒ Object
61 62 63 |
# File 'lib/rsx/cache.rb', line 61 def size @lock.synchronize { @entries.size } end |
#write(key, value, expires_in: nil) ⇒ Object
43 44 45 46 47 48 49 50 |
# File 'lib/rsx/cache.rb', line 43 def write(key, value, expires_in: nil) @lock.synchronize do @entries.delete(key) @entries[key] = [value, expires_in && (now + expires_in)] @entries.shift while @entries.size > @max_entries end value end |