Class: Foobara::LruCache

Inherits:
Object
  • Object
show all
Defined in:
foobara-lru-cache-0.0.2/lib/foobara/lru_cache.rb

Defined Under Namespace

Classes: Node

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(capacity = 10) ⇒ LruCache

Returns a new instance of LruCache.



16
17
18
19
20
21
# File 'foobara-lru-cache-0.0.2/lib/foobara/lru_cache.rb', line 16

def initialize(capacity = 10)
  @capacity = capacity
  @size = 0
  @key_to_node = {}
  @head = @tail = nil
end

Instance Attribute Details

#sizeObject (readonly)

Returns the value of attribute size.



14
15
16
# File 'foobara-lru-cache-0.0.2/lib/foobara/lru_cache.rb', line 14

def size
  @size
end

Instance Method Details

#cached(key) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'foobara-lru-cache-0.0.2/lib/foobara/lru_cache.rb', line 23

def cached(key)
  mutex.synchronize do
    if @key_to_node.key?(key)
      node = @key_to_node[key]
      move_node_to_front(node)
      return node.value
    end
  end

  value = yield
  mutex.synchronize do
    if @key_to_node.key?(key)
      node = @key_to_node[key]
      move_node_to_front(node)
    else
      node = Node.new(key, value)
      @key_to_node[key] = node
      prepend_node(node)
    end
  end

  value
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
# File 'foobara-lru-cache-0.0.2/lib/foobara/lru_cache.rb', line 47

def key?(key)
  @key_to_node.key?(key)
end

#reset!Object



51
52
53
54
55
56
57
# File 'foobara-lru-cache-0.0.2/lib/foobara/lru_cache.rb', line 51

def reset!
  mutex.synchronize do
    @size = 0
    @key_to_node.clear
    @head = @tail = nil
  end
end