Class: Karafka::Web::Ui::Lib::TtlCache
- Inherits:
-
Object
- Object
- Karafka::Web::Ui::Lib::TtlCache
- Includes:
- Core::Helpers::Time
- Defined in:
- lib/karafka/web/ui/lib/ttl_cache.rb
Overview
Note:
It is thread-safe
Ttl Cache for caching things in-memory
Instance Method Summary collapse
-
#clear ⇒ Object
Clears the whole cache.
-
#fetch(key) ⇒ Object
Reads from the cache and if value not present, will run the block and store its result in the cache.
-
#initialize(ttl) ⇒ TtlCache
constructor
A new instance of TtlCache.
-
#read(key) ⇒ Object
Reads data from the cache.
-
#write(key, value) ⇒ Object
Writes to the cache.
Constructor Details
#initialize(ttl) ⇒ TtlCache
Returns a new instance of TtlCache.
14 15 16 17 18 19 |
# File 'lib/karafka/web/ui/lib/ttl_cache.rb', line 14 def initialize(ttl) @ttl = ttl @times = {} @values = {} @mutex = Mutex.new end |
Instance Method Details
#clear ⇒ Object
Clears the whole cache
60 61 62 63 64 65 |
# File 'lib/karafka/web/ui/lib/ttl_cache.rb', line 60 def clear @mutex.synchronize do @times.clear @values.clear end end |
#fetch(key) ⇒ Object
Reads from the cache and if value not present, will run the block and store its result in the cache
49 50 51 52 53 54 55 56 57 |
# File 'lib/karafka/web/ui/lib/ttl_cache.rb', line 49 def fetch(key) @mutex.synchronize do evict return @values[key] if @values.key?(key) @values[key] = yield end end |
#read(key) ⇒ Object
Reads data from the cache
25 26 27 28 29 30 |
# File 'lib/karafka/web/ui/lib/ttl_cache.rb', line 25 def read(key) @mutex.synchronize do evict @values[key] end end |
#write(key, value) ⇒ Object
Writes to the cache
37 38 39 40 41 42 |
# File 'lib/karafka/web/ui/lib/ttl_cache.rb', line 37 def write(key, value) @mutex.synchronize do @times[key] = monotonic_now + @ttl @values[key] = value end end |