Class: Miscellany::LocalLruCache

Inherits:
Object
  • Object
show all
Defined in:
lib/miscellany/local_lru_cache.rb

Instance Method Summary collapse

Constructor Details

#initialize(max_size) ⇒ LocalLruCache

Returns a new instance of LocalLruCache.



3
4
5
6
# File 'lib/miscellany/local_lru_cache.rb', line 3

def initialize(max_size)
  @max_size = max_size
  @data = {}
end

Instance Method Details

#[](key) ⇒ Object



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

def [](key)
  found = true
  value = @data.delete(key){ found = false }
  if found
    @data[key] = value
  else
    nil
  end
end

#[]=(key, val) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/miscellany/local_lru_cache.rb', line 35

def []=(key,val)
  @data.delete(key)
  @data[key] = val
  if @data.length > @max_size
    @data.delete(@data.first[0])
  end
  val
end

#clearObject



58
59
60
# File 'lib/miscellany/local_lru_cache.rb', line 58

def clear
  @data.clear
end

#countObject



62
63
64
# File 'lib/miscellany/local_lru_cache.rb', line 62

def count
  @data.count
end

#delete(k) ⇒ Object



54
55
56
# File 'lib/miscellany/local_lru_cache.rb', line 54

def delete(k)
  @data.delete(k)
end

#eachObject



44
45
46
47
48
# File 'lib/miscellany/local_lru_cache.rb', line 44

def each
  to_a.each do |pair|
    yield pair
  end
end

#fetch(key) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/miscellany/local_lru_cache.rb', line 17

def fetch(key)
  if @data.key?(key)
    self[key]
  else
    self[key] = yield
  end
end

#max_size=(size) ⇒ Object

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
# File 'lib/miscellany/local_lru_cache.rb', line 8

def max_size=(size)
  raise ArgumentError.new(:max_size) if size < 1
  @max_size = size
  # Evict least-recently-used entries (oldest first) until we fit.
  while @data.size > @max_size
    @data.delete(@data.first[0])
  end
end

#to_aObject



50
51
52
# File 'lib/miscellany/local_lru_cache.rb', line 50

def to_a
  @data.to_a.reverse
end