Class: Rx::Cache::LRUCache

Inherits:
Object
  • Object
show all
Defined in:
lib/rx/cache/lru_cache.rb

Instance Method Summary collapse

Constructor Details

#initializeLRUCache

Returns a new instance of LRUCache.



6
7
8
9
10
11
12
# File 'lib/rx/cache/lru_cache.rb', line 6

def initialize
  @heap = Rx::Util::Heap.new do |a, b|
    a[1] < b[1]
  end
  @lock = Mutex.new
  @map  = Hash.new
end

Instance Method Details

#cache(k, expires_in = 60) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/rx/cache/lru_cache.rb', line 14

def cache(k, expires_in = 60)
  if value = get(k)
    return value
  end
  
  value = yield
  put(k, value, expires_in)
  value
end

#get(k) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/rx/cache/lru_cache.rb', line 24

def get(k)
  clean!

  lock.synchronize do
    map[k]
  end
end

#put(k, v, expires_in = 60) ⇒ Object



32
33
34
35
36
37
# File 'lib/rx/cache/lru_cache.rb', line 32

def put(k, v, expires_in = 60)
  lock.synchronize do
    map[k] = v
    heap << [k, Time.now + expires_in]
  end
end