Class: Caches::TTL

Inherits:
Object
  • Object
show all
Includes:
Accessible
Defined in:
lib/caches/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.



10
11
12
13
14
15
16
# File 'lib/caches/ttl.rb', line 10

def initialize(options = {})
  self.ttl      = options.fetch(:ttl) { 3600 }
  self.refresh  = !!(options.fetch(:refresh, false))
  self.data     = {}
  self.nodes    = LinkedList.new
  self.max_keys = options[:max_keys]
end

Instance Attribute Details

#refreshObject

Returns the value of attribute refresh.



8
9
10
# File 'lib/caches/ttl.rb', line 8

def refresh
  @refresh
end

#ttlObject

Returns the value of attribute ttl.



8
9
10
# File 'lib/caches/ttl.rb', line 8

def ttl
  @ttl
end

Instance Method Details

#[](key) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/caches/ttl.rb', line 18

def [](key)
  return nil unless data.has_key?(key)
  if current?(key)
    data[key][:value].tap {
      data[key][:time] = current_time if refresh
    }
  else
    delete(key)
    nil
  end
end

#[]=(key, val) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/caches/ttl.rb', line 30

def []=(key, val)
  if data.has_key?(key)
    node = data[key][:node]
    nodes.move_to_head(node)
  else
    if full?
      evicted_node = nodes.pop
      data.delete(evicted_node.value)
    end
    node = nodes.prepend(key)
  end
  data[key] = {time: current_time, value: val, node: node}
end

#delete(key) ⇒ Object



44
45
46
47
48
49
# File 'lib/caches/ttl.rb', line 44

def delete(key)
  node = data[key][:node]
  nodes.delete(node)
  hash = data.delete(key)
  hash.fetch(:value)
end

#keysObject



55
56
57
# File 'lib/caches/ttl.rb', line 55

def keys
  data.keys
end

#sizeObject



51
52
53
# File 'lib/caches/ttl.rb', line 51

def size
  nodes.length
end

#valuesObject



59
60
61
# File 'lib/caches/ttl.rb', line 59

def values
  data.values.map { |h| h.fetch(:value) }
end