Class: StatsLite::Cache

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCache

Returns a new instance of Cache.



7
8
9
# File 'lib/stats_lite/cache.rb', line 7

def initialize
  @map = {}
end

Instance Attribute Details

#mapObject (readonly)

Returns the value of attribute map.



5
6
7
# File 'lib/stats_lite/cache.rb', line 5

def map
  @map
end

Class Method Details

._gey_key(name) ⇒ Object



47
48
49
# File 'lib/stats_lite/cache.rb', line 47

def _gey_key(name)
  @cache.map[name]
end

._handle_expires(name, proc) ⇒ Object



38
39
40
41
# File 'lib/stats_lite/cache.rb', line 38

def _handle_expires(name, proc)
  @cache.map[name] = { timestamp: Time.now, value: proc.call }
  @cache.map[name][:value]
end

._set_key(name, proc) ⇒ Object



43
44
45
# File 'lib/stats_lite/cache.rb', line 43

def _set_key(name, proc)
  @cache.map[name] = proc.call
end

.fetch(name, proc, expires_s) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/stats_lite/cache.rb', line 12

def fetch(name, proc, expires_s)
  @cache ||= new

  existing = @cache.map[name] if @cache.map.has_key?(name)

  if existing
    if existing.is_a?(Hash) && existing.has_key?(:timestamp)
      if Time.now - existing[:timestamp] > expires_s
        _handle_expires(name, proc)
      else
        existing[:value]
      end
    elsif expires_s > 0
      _handle_expires(name, proc)
    else
      _gey_key(name)
    end
  else
    if expires_s > 0
      _handle_expires(name, proc)
    else
      _set_key(name, proc)
    end
  end
end