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

Modules: Item

Instance Method Summary collapse

Constructor Details

#initialize(capacity = 20) ⇒ LRUCache

Returns a new instance of LRUCache.



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

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

Instance Method Details

#delete(key) ⇒ Object



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

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

#delete_if(&block) ⇒ Object



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

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

#fetch(key, default_value = nil) ⇒ Object



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

def fetch(key, default_value=nil)
  if item = @store[key]
    touch(item)
    item
  else
    default_value
  end
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#store(key, item) ⇒ Object



42
43
44
45
46
# File 'lib/wee/lru_cache.rb', line 42

def store(key, item)
  touch(item)
  compact()
  @store[key] = item
end