Class: RPCMapper::Cacheable::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/rpc_mapper/cacheable/store.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(default_longevity) ⇒ Store

TRP: Specify the default longevity of a cache entry in seconds



9
10
11
12
# File 'lib/rpc_mapper/cacheable/store.rb', line 9

def initialize(default_longevity)
  @store = {}
  @default_longevity = default_longevity
end

Instance Attribute Details

#default_longevityObject

Returns the value of attribute default_longevity.



6
7
8
# File 'lib/rpc_mapper/cacheable/store.rb', line 6

def default_longevity
  @default_longevity
end

#storeObject (readonly)

Returns the value of attribute store.



5
6
7
# File 'lib/rpc_mapper/cacheable/store.rb', line 5

def store
  @store
end

Instance Method Details

#clear(key = nil) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/rpc_mapper/cacheable/store.rb', line 14

def clear(key=nil)
  if key
    @store.delete(key)
  else
    @store.each do |key, entry|
      clear(key) if key && (!entry || entry.expired?)
    end
  end
end

#read(key) ⇒ Object

TRP: Returns value if a cache hit and the entry is not expired, nil otherwise



25
26
27
28
29
30
31
32
33
34
# File 'lib/rpc_mapper/cacheable/store.rb', line 25

def read(key)
  if entry = @store[key]
    if entry.expired?
      clear(key)
      nil
    else
      entry.value
    end
  end
end

#write(key, value, expires = Time.now + default_longevity) ⇒ Object

TRP: Write a new cache value and optionally specify the expire time

this also will clear all expired items out of the store to keep memory consumption as low as possible


38
39
40
41
# File 'lib/rpc_mapper/cacheable/store.rb', line 38

def write(key, value, expires=Time.now + default_longevity)
  clear
  @store[key] = Entry.new(value, expires)
end