Class: Cacheable::CacheAdapters::MemoryAdapter
- Inherits:
-
Object
- Object
- Cacheable::CacheAdapters::MemoryAdapter
- Defined in:
- lib/cacheable/cache_adapters/memory_adapter.rb
Instance Method Summary collapse
- #clear ⇒ Object
- #delete(key) ⇒ Object
- #exist?(key) ⇒ Boolean
-
#fetch(key, _options = {}) ⇒ Object
NOTE: yield is intentionally called inside the lock to prevent thundering herd — only one thread computes a missing value while others wait.
-
#initialize ⇒ MemoryAdapter
constructor
A new instance of MemoryAdapter.
- #read(key) ⇒ Object
- #write(key, value) ⇒ Object
Constructor Details
#initialize ⇒ MemoryAdapter
Returns a new instance of MemoryAdapter.
8 9 10 11 |
# File 'lib/cacheable/cache_adapters/memory_adapter.rb', line 8 def initialize @monitor = Monitor.new clear end |
Instance Method Details
#clear ⇒ Object
45 46 47 |
# File 'lib/cacheable/cache_adapters/memory_adapter.rb', line 45 def clear @monitor.synchronize { @cache = {} } end |
#delete(key) ⇒ Object
36 37 38 39 40 41 42 43 |
# File 'lib/cacheable/cache_adapters/memory_adapter.rb', line 36 def delete(key) @monitor.synchronize do return false unless @cache.key?(key) @cache.delete(key) true end end |
#exist?(key) ⇒ Boolean
21 22 23 |
# File 'lib/cacheable/cache_adapters/memory_adapter.rb', line 21 def exist?(key) @monitor.synchronize { @cache.key?(key) } end |
#fetch(key, _options = {}) ⇒ Object
NOTE: yield is intentionally called inside the lock to prevent thundering herd — only one thread computes a missing value while others wait. This is acceptable for a simple in-memory adapter; production use cases needing high concurrency should use a real cache backend via CacheAdapter.
28 29 30 31 32 33 34 |
# File 'lib/cacheable/cache_adapters/memory_adapter.rb', line 28 def fetch(key, = {}) @monitor.synchronize do return @cache[key] if @cache.key?(key) @cache[key] = yield end end |
#read(key) ⇒ Object
13 14 15 |
# File 'lib/cacheable/cache_adapters/memory_adapter.rb', line 13 def read(key) @monitor.synchronize { @cache[key] } end |
#write(key, value) ⇒ Object
17 18 19 |
# File 'lib/cacheable/cache_adapters/memory_adapter.rb', line 17 def write(key, value) @monitor.synchronize { @cache[key] = value } end |