class Rx::Cache::InMemoryCache

Attributes

heap[R]
lock[R]
map[R]

Public Class Methods

new() click to toggle source
# File lib/rx/cache/in_memory_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

Public Instance Methods

cache(k, expires_in = 60) { || ... } click to toggle source
# File lib/rx/cache/in_memory_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) click to toggle source
# File lib/rx/cache/in_memory_cache.rb, line 24
def get(k)
  clean!

  lock.synchronize do
    map[k]
  end
end
put(k, v, expires_in = 60) click to toggle source
# File lib/rx/cache/in_memory_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

Private Instance Methods

clean!() click to toggle source
# File lib/rx/cache/in_memory_cache.rb, line 42
def clean!
  lock.synchronize do
    while !heap.peek.nil? && heap.peek[1] < Time.now
      map.delete(heap.pop[0])
    end
  end
end