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
26 27 28 29 30 31 32 33 34 |
# File 'lib/miscellany/local_lru_cache.rb', line 26 def [](key) found = true value = @data.delete(key){ found = false } if found @data[key] = value else nil end end |
#[]=(key, val) ⇒ Object
36 37 38 39 40 41 42 43 |
# File 'lib/miscellany/local_lru_cache.rb', line 36 def []=(key,val) @data.delete(key) @data[key] = val if @data.length > @max_size @data.delete(@data.first[0]) end val end |
#clear ⇒ Object
59 60 61 |
# File 'lib/miscellany/local_lru_cache.rb', line 59 def clear @data.clear end |
#count ⇒ Object
63 64 65 |
# File 'lib/miscellany/local_lru_cache.rb', line 63 def count @data.count end |
#delete(k) ⇒ Object
55 56 57 |
# File 'lib/miscellany/local_lru_cache.rb', line 55 def delete(k) @data.delete(k) end |
#each ⇒ Object
45 46 47 48 49 |
# File 'lib/miscellany/local_lru_cache.rb', line 45 def each @data.reverse.each do |pair| yield pair end end |
#fetch(key) ⇒ Object
18 19 20 21 22 23 24 |
# File 'lib/miscellany/local_lru_cache.rb', line 18 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 16 |
# File 'lib/miscellany/local_lru_cache.rb', line 8 def max_size=(size) raise ArgumentError.new(:max_size) if @max_size < 1 @max_size = size if @max_size < @data.size @data.keys[0..@max_size-@data.size].each do |k| @data.delete(k) end end end |
#to_a ⇒ Object
51 52 53 |
# File 'lib/miscellany/local_lru_cache.rb', line 51 def to_a @data.to_a.reverse end |