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 ⇒ void
Clear all values from the cache.
-
#delete(key) ⇒ void
Delete a value from the cache.
-
#fetch(key, expires_in: nil) { ... } ⇒ Object?
Fetch a value from the cache.
-
#initialize ⇒ SupportTableCache::MemoryCache
constructor
Create a new memory cache.
-
#read(key) ⇒ Object?
Read a value from the cache.
-
#write(key, value, expires_in: nil) ⇒ void
Write a value to the cache.
Constructor Details
#initialize ⇒ SupportTableCache::MemoryCache
Create a new memory cache.
14 15 16 17 |
# File 'lib/support_table_cache/memory_cache.rb', line 14 def initialize @cache = {} @mutex = Mutex.new end |
Instance Method Details
#clear ⇒ void
This method returns an undefined value.
Clear all values from the cache.
75 76 77 |
# File 'lib/support_table_cache/memory_cache.rb', line 75 def clear @cache.clear end |
#delete(key) ⇒ void
This method returns an undefined value.
Delete a value from the cache.
68 69 70 |
# File 'lib/support_table_cache/memory_cache.rb', line 68 def delete(key) @cache.delete(key) end |
#fetch(key, expires_in: nil) { ... } ⇒ Object?
Fetch a value from the cache. If the key is not found or has expired, yields to get a new value.
25 26 27 28 29 30 31 32 33 34 |
# File 'lib/support_table_cache/memory_cache.rb', line 25 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?
Read a value from the cache.
40 41 42 |
# File 'lib/support_table_cache/memory_cache.rb', line 40 def read(key) fetch(key) end |
#write(key, value, expires_in: nil) ⇒ void
This method returns an undefined value.
Write a value to the cache.
50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/support_table_cache/memory_cache.rb', line 50 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 |