Class: Evanescence::Cache
- Inherits:
-
Object
- Object
- Evanescence::Cache
- Defined in:
- lib/evanescence/cache.rb
Overview
Simple implementation of caching
Instance Method Summary collapse
- #clear ⇒ Object
- #count ⇒ Object
- #delete(key) ⇒ Object
-
#initialize(max_size:) ⇒ Cache
constructor
A new instance of Cache.
- #read(key) ⇒ Object
- #to_h ⇒ Object
- #write(key, val) ⇒ Object
Constructor Details
#initialize(max_size:) ⇒ Cache
Returns a new instance of Cache.
4 5 6 7 |
# File 'lib/evanescence/cache.rb', line 4 def initialize(max_size:) @items = {} @max_size = max_size end |
Instance Method Details
#clear ⇒ Object
33 34 35 36 37 |
# File 'lib/evanescence/cache.rb', line 33 def clear count_before_clear = count items.clear count_before_clear end |
#count ⇒ Object
39 40 41 |
# File 'lib/evanescence/cache.rb', line 39 def count items.count end |
#delete(key) ⇒ Object
29 30 31 |
# File 'lib/evanescence/cache.rb', line 29 def delete(key) items.delete(key) end |
#read(key) ⇒ Object
21 22 23 24 25 26 27 |
# File 'lib/evanescence/cache.rb', line 21 def read(key) item = items[key] return unless item item[1] += 1 if max_size item.first end |
#to_h ⇒ Object
9 10 11 |
# File 'lib/evanescence/cache.rb', line 9 def to_h items.transform_values(&:first) end |
#write(key, val) ⇒ Object
13 14 15 16 17 18 19 |
# File 'lib/evanescence/cache.rb', line 13 def write(key, val) reject_least_used_item if max_size existing_item = items[key] existing_item ? update_value(existing_item, val) : items[key] = [val, 1] items[key].first end |