Class: JSONP3::LRUCache
- Inherits:
-
Object
- Object
- JSONP3::LRUCache
- Defined in:
- lib/json_p3/cache.rb
Overview
A least recently used cache relying on Ruby hash insertion order.
Instance Attribute Summary collapse
-
#max_size ⇒ Object
readonly
Returns the value of attribute max_size.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Return the cached value or nil if key does not exist.
- #[]=(key, value) ⇒ Object
-
#initialize(max_size = 128) ⇒ LRUCache
constructor
A new instance of LRUCache.
- #keys ⇒ Object
- #length ⇒ Object
Constructor Details
#initialize(max_size = 128) ⇒ LRUCache
Returns a new instance of LRUCache.
8 9 10 11 |
# File 'lib/json_p3/cache.rb', line 8 def initialize(max_size = 128) @data = {} @max_size = max_size end |
Instance Attribute Details
#max_size ⇒ Object (readonly)
Returns the value of attribute max_size.
6 7 8 |
# File 'lib/json_p3/cache.rb', line 6 def max_size @max_size end |
Instance Method Details
#[](key) ⇒ Object
Return the cached value or nil if key does not exist.
14 15 16 17 18 19 20 21 |
# File 'lib/json_p3/cache.rb', line 14 def [](key) val = @data[key] return nil if val.nil? @data.delete(key) @data[key] = val val end |
#[]=(key, value) ⇒ Object
23 24 25 26 27 28 29 30 |
# File 'lib/json_p3/cache.rb', line 23 def []=(key, value) if @data.key?(key) @data.delete(key) elsif @data.length >= @max_size @data.delete((@data.first || raise)[0]) end @data[key] = value end |
#keys ⇒ Object
36 37 38 |
# File 'lib/json_p3/cache.rb', line 36 def keys @data.keys end |
#length ⇒ Object
32 33 34 |
# File 'lib/json_p3/cache.rb', line 32 def length @data.length end |