Class: Underpass::Cache
- Inherits:
-
Object
- Object
- Underpass::Cache
- Defined in:
- lib/underpass/cache.rb
Overview
Simple in-memory cache with TTL expiration.
Instance Method Summary collapse
-
#clear ⇒ void
Removes all entries from the cache.
-
#fetch(key) ⇒ Object?
Retrieves a cached value by key if it has not expired.
-
#initialize(ttl: 300) ⇒ Cache
constructor
Creates a new cache instance.
-
#store(key, value) ⇒ Hash
Stores a value in the cache.
Constructor Details
#initialize(ttl: 300) ⇒ Cache
Creates a new cache instance.
12 13 14 15 |
# File 'lib/underpass/cache.rb', line 12 def initialize(ttl: 300) @store = {} @ttl = ttl end |
Instance Method Details
#clear ⇒ void
This method returns an undefined value.
Removes all entries from the cache.
41 42 43 |
# File 'lib/underpass/cache.rb', line 41 def clear @store.clear end |
#fetch(key) ⇒ Object?
Retrieves a cached value by key if it has not expired.
21 22 23 24 25 26 27 |
# File 'lib/underpass/cache.rb', line 21 def fetch(key) entry = @store[key] return nil unless entry return nil if Time.now - entry[:time] > @ttl entry[:value] end |
#store(key, value) ⇒ Hash
Stores a value in the cache.
34 35 36 |
# File 'lib/underpass/cache.rb', line 34 def store(key, value) @store[key] = { value: value, time: Time.now } end |