Class: Mayak::Caching::LRUCache
- Inherits:
-
Object
- Object
- Mayak::Caching::LRUCache
- Extended by:
- T::Generic, T::Helpers, T::Sig
- Includes:
- Mayak::Cache
- Defined in:
- lib/mayak/caching/lru_cache.rb
Constant Summary collapse
- Key =
type_member
- Value =
type_member
Instance Attribute Summary collapse
-
#max_size ⇒ Object
readonly
Returns the value of attribute max_size.
Instance Method Summary collapse
- #clear ⇒ Object
- #delete(key) ⇒ Object
- #fetch(key, &blk) ⇒ Object
-
#initialize(max_size:) ⇒ LRUCache
constructor
A new instance of LRUCache.
- #read(key) ⇒ Object
- #write(key, value) ⇒ Object
Constructor Details
#initialize(max_size:) ⇒ LRUCache
Returns a new instance of LRUCache.
20 21 22 23 24 25 26 |
# File 'lib/mayak/caching/lru_cache.rb', line 20 def initialize(max_size:) @storage = T.let({}, T::Hash[Key, Value]) if max_size <= 0 raise ArgumentError.new("max_size should be a positive integer") end @max_size = T.let(max_size, Integer) end |
Instance Attribute Details
#max_size ⇒ Object (readonly)
Returns the value of attribute max_size.
17 18 19 |
# File 'lib/mayak/caching/lru_cache.rb', line 17 def max_size @max_size end |
Instance Method Details
#clear ⇒ Object
53 54 55 |
# File 'lib/mayak/caching/lru_cache.rb', line 53 def clear @storage.clear end |
#delete(key) ⇒ Object
58 59 60 |
# File 'lib/mayak/caching/lru_cache.rb', line 58 def delete(key) @storage.delete(key) end |
#fetch(key, &blk) ⇒ Object
44 45 46 47 48 49 50 |
# File 'lib/mayak/caching/lru_cache.rb', line 44 def fetch(key, &blk) return T.must(@storage[key]) if @storage.has_key?(key) value = blk.call write(key, value) value end |
#read(key) ⇒ Object
29 30 31 |
# File 'lib/mayak/caching/lru_cache.rb', line 29 def read(key) @storage[key] end |
#write(key, value) ⇒ Object
34 35 36 37 38 39 40 41 |
# File 'lib/mayak/caching/lru_cache.rb', line 34 def write(key, value) if @storage.size == max_size && !@storage.key?(key) evict! elsif @storage.key?(key) @storage.delete(key) end @storage[key] = value end |