Class: Rx::Cache::MapCache

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

Instance Method Summary collapse

Constructor Details

#initializeMapCache

Returns a new instance of MapCache.



6
7
8
9
# File 'lib/rx/cache/map_cache.rb', line 6

def initialize
  @data = {}
  @lock = Mutex.new
end

Instance Method Details

#cache(k, expires_in = 60) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/rx/cache/map_cache.rb', line 11

def cache(k, expires_in = 60)
  unless (value = get(k)).nil?
    return value
  end

  value = yield
  put(k, value, expires_in)
  value
end

#get(k) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rx/cache/map_cache.rb', line 21

def get(k)
  lock.synchronize do
    value = data[k]
    return nil unless value

    if value[1] < Time.now
      data.delete(k)
      return nil
    end
    
    value[0]
  end
end

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



35
36
37
38
39
# File 'lib/rx/cache/map_cache.rb', line 35

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