Class: Geogov::LruCache

Inherits:
Object
  • Object
show all
Defined in:
lib/geogov/utils.rb

Overview

Dead simple and inefficient LRU cache In no way thread-safe

Instance Method Summary collapse

Constructor Details

#initialize(size = 100) ⇒ LruCache

Returns a new instance of LruCache.



33
34
35
36
37
# File 'lib/geogov/utils.rb', line 33

def initialize(size = 100)
  @size = size
  @bucket1 = {}
  @bucket2 = {}
end

Instance Method Details

#[](key) ⇒ Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/geogov/utils.rb', line 50

def [](key)
  if @bucket1[key]
    return @bucket1[key]
  elsif @bucket2[key]
    obj = @bucket2.delete[key]
    @bucket1[key] = obj
    swizzle if @bucket1.size > @size
    return obj
  end
end

#[]=(key, obj) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/geogov/utils.rb', line 39

def []=(key,obj)
  if @bucket1[key]
    @bucket1[key] = obj
  elsif @bucket2[key]
    @bucket2[key] = obj
  else
    @bucket1[key] = obj
    swizzle if @bucket1.size > @size
  end
end

#swizzleObject



61
62
63
64
# File 'lib/geogov/utils.rb', line 61

def swizzle
  @bucket2 = @bucket1
  @bucket1 = {}
end