Class: Caches::LRU

Inherits:
Object
  • Object
show all
Includes:
Accessible
Defined in:
lib/caches/lru.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Accessible

#fetch, #memoize

Constructor Details

#initialize(options = {}) ⇒ LRU

Returns a new instance of LRU.



9
10
11
12
13
# File 'lib/caches/lru.rb', line 9

def initialize(options = {})
  self.max_keys = options.fetch(:max_keys, 20)
  self.data     = {}
  self.keys = LinkedList.new
end

Instance Attribute Details

#max_keysObject

Returns the value of attribute max_keys.



7
8
9
# File 'lib/caches/lru.rb', line 7

def max_keys
  @max_keys
end

Instance Method Details

#[](key) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/caches/lru.rb', line 15

def [](key)
  return nil if max_keys.zero?
  return nil unless data.has_key?(key)
  value, node = data[key]
  keys.move_to_head(node)
  value
end

#[]=(key, val) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/caches/lru.rb', line 23

def []=(key, val)
  return nil if max_keys.zero?
  if data.has_key?(key)
    data[key][0] = val
  else
    node = keys.prepend(key)
    data[key] = [val, node]
  end
  prune
  val
end

#sizeObject



35
36
37
# File 'lib/caches/lru.rb', line 35

def size
  keys.length
end