Class: Wee::LRUCache

Inherits:
Object show all
Defined in:
lib/wee/lru_cache.rb

Overview

Implementation of a Least Recently Used (LRU) Cache

Direct Known Subclasses

Application::SessionCache

Defined Under Namespace

Classes: Item

Instance Method Summary collapse

Constructor Details

#initialize(capacity = 20, &replace_callback) ⇒ LRUCache

Returns a new instance of LRUCache.



13
14
15
16
17
18
# File 'lib/wee/lru_cache.rb', line 13

def initialize(capacity=20, &replace_callback)
  @capacity = capacity
  @replace_callback = replace_callback
  @store = Hash.new
  @time = 0
end

Instance Method Details

#delete(key) ⇒ Object



24
25
26
# File 'lib/wee/lru_cache.rb', line 24

def delete(key)
  @store.delete(key)
end

#delete_ifObject



28
29
30
31
32
# File 'lib/wee/lru_cache.rb', line 28

def delete_if
  @store.delete_if {|id, item|
    yield id, item.value
  }
end

#each(&block) ⇒ Object



65
66
67
# File 'lib/wee/lru_cache.rb', line 65

def each(&block)
  @store.each(&block)
end

#fetch(key, default_value = nil) ⇒ Object Also known as: []



34
35
36
37
38
39
40
41
# File 'lib/wee/lru_cache.rb', line 34

def fetch(key, default_value=nil)
  if item = @store[key]
    item.time = (@time += 1)
    item.value
  else
    default_value
  end
end

#garbage_collectObject



62
63
# File 'lib/wee/lru_cache.rb', line 62

def garbage_collect
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/wee/lru_cache.rb', line 20

def has_key?(key)
  @store.has_key?(key)
end

#store(key, value) ⇒ Object Also known as: []=



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/wee/lru_cache.rb', line 43

def store(key, value)
  if item = @store[key]
    # update item only
    item.time = (@time += 1)
    item.value = value
  else
    # insert new item
    item = Item.new
    item.time = (@time += 1)
    item.value = value
    garbage_collect() if @store.size >= @capacity
    while @store.size >= @capacity 
      old_item = @store.delete(min_key()) || raise
      @replace_callback.call(old_item) if @replace_callback
    end
    @store[key] = item
  end
end