Class: Miscellany::LocalLruCache
- Inherits:
-
Object
- Object
- Miscellany::LocalLruCache
- Defined in:
- lib/miscellany/local_lru_cache.rb
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, val) ⇒ Object
- #clear ⇒ Object
- #count ⇒ Object
- #delete(k) ⇒ Object
- #each ⇒ Object
- #fetch(key) ⇒ Object
-
#initialize(max_size) ⇒ LocalLruCache
constructor
A new instance of LocalLruCache.
- #max_size=(size) ⇒ Object
- #to_a ⇒ Object
Constructor Details
#initialize(max_size) ⇒ LocalLruCache
Returns a new instance of LocalLruCache.
3 4 5 6 |
# File 'lib/miscellany/local_lru_cache.rb', line 3 def initialize(max_size) @max_size = max_size @data = {} end |
Instance Method Details
#[](key) ⇒ Object
25 26 27 28 29 30 31 32 33 |
# File 'lib/miscellany/local_lru_cache.rb', line 25 def [](key) found = true value = @data.delete(key){ found = false } if found @data[key] = value else nil end end |
#[]=(key, val) ⇒ Object
35 36 37 38 39 40 41 42 |
# File 'lib/miscellany/local_lru_cache.rb', line 35 def []=(key,val) @data.delete(key) @data[key] = val if @data.length > @max_size @data.delete(@data.first[0]) end val end |
#clear ⇒ Object
58 59 60 |
# File 'lib/miscellany/local_lru_cache.rb', line 58 def clear @data.clear end |
#count ⇒ Object
62 63 64 |
# File 'lib/miscellany/local_lru_cache.rb', line 62 def count @data.count end |
#delete(k) ⇒ Object
54 55 56 |
# File 'lib/miscellany/local_lru_cache.rb', line 54 def delete(k) @data.delete(k) end |
#each ⇒ Object
44 45 46 47 48 |
# File 'lib/miscellany/local_lru_cache.rb', line 44 def each to_a.each do |pair| yield pair end end |
#fetch(key) ⇒ Object
17 18 19 20 21 22 23 |
# File 'lib/miscellany/local_lru_cache.rb', line 17 def fetch(key) if @data.key?(key) self[key] else self[key] = yield end end |
#max_size=(size) ⇒ Object
8 9 10 11 12 13 14 15 |
# File 'lib/miscellany/local_lru_cache.rb', line 8 def max_size=(size) raise ArgumentError.new(:max_size) if size < 1 @max_size = size # Evict least-recently-used entries (oldest first) until we fit. while @data.size > @max_size @data.delete(@data.first[0]) end end |
#to_a ⇒ Object
50 51 52 |
# File 'lib/miscellany/local_lru_cache.rb', line 50 def to_a @data.to_a.reverse end |