Class: SupportTableCache::MemoryCache
- Inherits:
-
Object
- Object
- SupportTableCache::MemoryCache
- Defined in:
- lib/support_table_cache/memory_cache.rb
Overview
An optimized cache implementation that can be used when all records can easily fit in memory and are never changed. It is intended for use with small, static support tables only.
This cache will not store nil values. This is to prevent the cache from filling up with cache misses because there is no purging mechanism.
Instance Method Summary collapse
- #clear ⇒ Object
- #delete(key) ⇒ Object
- #fetch(key, expires_in: nil) ⇒ Object
-
#initialize ⇒ MemoryCache
constructor
A new instance of MemoryCache.
- #read(key) ⇒ Object
- #write(key, value, expires_in: nil) ⇒ Object
Constructor Details
#initialize ⇒ MemoryCache
Returns a new instance of MemoryCache.
11 12 13 14 |
# File 'lib/support_table_cache/memory_cache.rb', line 11 def initialize @cache = {} @mutex = Mutex.new end |
Instance Method Details
#clear ⇒ Object
49 50 51 |
# File 'lib/support_table_cache/memory_cache.rb', line 49 def clear @cache.clear end |
#delete(key) ⇒ Object
45 46 47 |
# File 'lib/support_table_cache/memory_cache.rb', line 45 def delete(key) @cache.delete(key) end |
#fetch(key, expires_in: nil) ⇒ Object
16 17 18 19 20 21 22 23 24 25 |
# File 'lib/support_table_cache/memory_cache.rb', line 16 def fetch(key, expires_in: nil) serialized_value, expire_at = @cache[key] if serialized_value.nil? || (expire_at && expire_at < Process.clock_gettime(Process::CLOCK_MONOTONIC)) value = yield if block_given? return nil if value.nil? write(key, value, expires_in: expires_in) serialized_value = Marshal.dump(value) end Marshal.load(serialized_value) end |
#read(key) ⇒ Object
27 28 29 |
# File 'lib/support_table_cache/memory_cache.rb', line 27 def read(key) fetch(key) end |
#write(key, value, expires_in: nil) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/support_table_cache/memory_cache.rb', line 31 def write(key, value, expires_in: nil) return if value.nil? if expires_in expire_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) + expires_in end serialized_value = Marshal.dump(value) @mutex.synchronize do @cache[key] = [serialized_value, expire_at] end end |