Class: Cosmo::Utils::TTLCache
- Inherits:
-
Object
- Object
- Cosmo::Utils::TTLCache
- Defined in:
- lib/cosmo/utils/ttl_cache.rb
Instance Method Summary collapse
- #fetch(key, ttl: nil) ⇒ Object
- #get(key) ⇒ Object
-
#initialize ⇒ TTLCache
constructor
A new instance of TTLCache.
- #set(key, value, ttl: nil) ⇒ Object
Constructor Details
#initialize ⇒ TTLCache
Returns a new instance of TTLCache.
6 7 8 |
# File 'lib/cosmo/utils/ttl_cache.rb', line 6 def initialize @store = {} end |
Instance Method Details
#fetch(key, ttl: nil) ⇒ Object
21 22 23 24 25 26 27 |
# File 'lib/cosmo/utils/ttl_cache.rb', line 21 def fetch(key, ttl: nil) return get(key) if key?(key) result = yield set(key, result, ttl: ttl) result end |
#get(key) ⇒ Object
15 16 17 18 19 |
# File 'lib/cosmo/utils/ttl_cache.rb', line 15 def get(key) return unless key?(key) @store[key].first end |
#set(key, value, ttl: nil) ⇒ Object
10 11 12 13 |
# File 'lib/cosmo/utils/ttl_cache.rb', line 10 def set(key, value, ttl: nil) @store[key] = [value, ttl ? Time.now + ttl : nil] value end |