Class: HashCache::TTL

Inherits:
Object
  • Object
show all
Includes:
Accessible
Defined in:
lib/hash_cache/ttl.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Accessible

#fetch, #memoize

Constructor Details

#initialize(options = {}) ⇒ TTL

Returns a new instance of TTL.



8
9
10
11
12
# File 'lib/hash_cache/ttl.rb', line 8

def initialize(options = {})
  self.ttl     = options.fetch(:ttl) { 3600 }
  self.refresh = !!(options.fetch(:refresh, false))
  self.data    = {}
end

Instance Attribute Details

#refreshObject

Returns the value of attribute refresh.



6
7
8
# File 'lib/hash_cache/ttl.rb', line 6

def refresh
  @refresh
end

#ttlObject

Returns the value of attribute ttl.



6
7
8
# File 'lib/hash_cache/ttl.rb', line 6

def ttl
  @ttl
end

Instance Method Details

#[](key) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/hash_cache/ttl.rb', line 14

def [](key)
  return nil unless data.has_key?(key)
  if (current_time - data[key][:time]) < ttl
    data[key][:time] = current_time if refresh
    data[key][:value]
  else
    data.delete(key)
    nil
  end
end

#[]=(key, val) ⇒ Object



25
26
27
# File 'lib/hash_cache/ttl.rb', line 25

def []=(key, val)
  data[key] = {time: current_time, value: val}
end

#sizeObject



29
30
31
# File 'lib/hash_cache/ttl.rb', line 29

def size
  data.keys.length
end