Class: CacheLib::LruCache
Instance Attribute Summary
Attributes inherited from BasicCache
#limit
Instance Method Summary
collapse
Methods inherited from BasicCache
#clear, #each, #evict, #expire, #initialize_copy, #inspect, #key?, #keys, #raw, #size, #to_a, #values
Constructor Details
#initialize(*args) ⇒ LruCache
Returns a new instance of LruCache.
3
4
5
6
7
8
9
10
11
12
|
# File 'lib/cache_lib/lru_cache.rb', line 3
def initialize(*args)
limit, _ = args
fail ArgumentError, "Cache Limit must be 1 or greater: #{limit}" if
limit.nil? || limit < 1
@limit = limit
@cache = UtilHash.new
end
|
Instance Method Details
#fetch(key) ⇒ Object
48
49
50
51
52
53
54
55
56
|
# File 'lib/cache_lib/lru_cache.rb', line 48
def fetch(key)
has_key = true
value = @cache.delete(key) { has_key = false }
if has_key
@cache[key] = value
else
yield if block_given?
end
end
|
#get(key) ⇒ Object
27
28
29
30
31
32
33
34
35
|
# File 'lib/cache_lib/lru_cache.rb', line 27
def get(key)
has_key = true
value = @cache.delete(key) { has_key = false }
if has_key
@cache[key] = value
else
miss(key, yield)
end
end
|
#limit=(args) ⇒ Object
14
15
16
17
18
19
20
21
22
23
24
25
|
# File 'lib/cache_lib/lru_cache.rb', line 14
def limit=(args)
limit, _ = args
limit ||= @limit
fail ArgumentError, "Cache Limit must be 1 or greater: #{limit}" if
limit.nil? || limit < 1
@limit = limit
resize
end
|
#lookup(key) ⇒ Object
Also known as:
[]
42
43
44
45
46
|
# File 'lib/cache_lib/lru_cache.rb', line 42
def lookup(key)
has_key = true
value = @cache.delete(key) { has_key = false }
@cache[key] = value if has_key
end
|
#store(key, value) ⇒ Object
Also known as:
[]=
37
38
39
40
|
# File 'lib/cache_lib/lru_cache.rb', line 37
def store(key, value)
@cache.delete(key)
miss(key, value)
end
|