Class: Sinarey::LruCache
- Inherits:
-
Object
- Object
- Sinarey::LruCache
- Defined in:
- lib/sinarey_cache/lru_redux/cache.rb,
lib/sinarey_cache/lru_redux/cache19.rb
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, val) ⇒ Object
- #clear ⇒ Object
- #count ⇒ Object
- #delete(k) ⇒ Object
- #each ⇒ Object (also: #each_unsafe)
- #fetch(key) ⇒ Object
- #getset(key) ⇒ Object
-
#initialize(max_size) ⇒ LruCache
constructor
A new instance of LruCache.
- #max_size=(size) ⇒ Object
- #to_a ⇒ Object
-
#valid? ⇒ Boolean
for cache validation only, ensures all is sound.
Constructor Details
#initialize(max_size) ⇒ LruCache
3 4 5 6 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 3 def initialize(max_size) @max_size = max_size @data = {} end |
Instance Method Details
#[](key) ⇒ Object
40 41 42 43 44 45 46 47 48 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 40 def [](key) found = true value = @data.delete(key){ found = false } if found @data[key] = value else nil end end |
#[]=(key, val) ⇒ Object
50 51 52 53 54 55 56 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 50 def []=(key,val) @data.delete(key) @data[key] = val # this may seem odd see: http://bugs.ruby-lang.org/issues/8312 @data.delete(@data.first[0]) if @data.length > @max_size val end |
#clear ⇒ Object
77 78 79 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 77 def clear @data.clear end |
#count ⇒ Object
81 82 83 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 81 def count @data.count end |
#delete(k) ⇒ Object
73 74 75 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 73 def delete(k) @data.delete(k) end |
#each ⇒ Object Also known as: each_unsafe
58 59 60 61 62 63 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 58 def each array = @data.to_a array.reverse!.each do |pair| yield pair end end |
#fetch(key) ⇒ Object
30 31 32 33 34 35 36 37 38 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 30 def fetch(key) found = true value = @data.delete(key){ found = false } if found @data[key] = value else yield if block_given? end end |
#getset(key) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 18 def getset(key) found = true value = @data.delete(key){ found = false } if found @data[key] = value else result = @data[key] = yield @data.delete(@data.first[0]) if @data.length > @max_size result end end |
#max_size=(size) ⇒ Object
8 9 10 11 12 13 14 15 16 |
# File 'lib/sinarey_cache/lru_redux/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
68 69 70 71 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 68 def to_a array = @data.to_a array.reverse! end |
#valid? ⇒ Boolean
for cache validation only, ensures all is sound
87 88 89 |
# File 'lib/sinarey_cache/lru_redux/cache.rb', line 87 def valid? true end |