Class: CacheLib::LruCache

Inherits:
BasicCache show all
Defined in:
lib/cache_lib/lru_cache.rb

Direct Known Subclasses

SafeLruCache

Instance Attribute Summary

Attributes inherited from BasicCache

#limit

Instance Method Summary collapse

Methods inherited from BasicCache

#clear, #each, #evict, #initialize_copy, #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



46
47
48
49
50
51
52
53
54
# File 'lib/cache_lib/lru_cache.rb', line 46

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



25
26
27
28
29
30
31
32
33
# File 'lib/cache_lib/lru_cache.rb', line 25

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

#inspectObject



56
57
58
59
# File 'lib/cache_lib/lru_cache.rb', line 56

def inspect
  "#{self.class} with a limit of #{@limit} "\
  "currently caching #{@cache.size} items."
end

#limit=(args) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/cache_lib/lru_cache.rb', line 14

def limit=(args)
  limit, _ = args

  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: []



40
41
42
43
44
# File 'lib/cache_lib/lru_cache.rb', line 40

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: []=



35
36
37
38
# File 'lib/cache_lib/lru_cache.rb', line 35

def store(key, value)
  @cache.delete(key)
  miss(key, value)
end