Class: BasicCache::TimeCache

Inherits:
Cache
  • Object
show all
Defined in:
lib/basiccache/caches/timecache.rb

Overview

Time-based cache object

Instance Attribute Summary collapse

Attributes inherited from Cache

#store

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ TimeCache

Generate an empty store, with a default lifetime of 60 seconds



17
18
19
20
21
# File 'lib/basiccache/caches/timecache.rb', line 17

def initialize(params = {})
  params = { store: params } unless params.is_a? Hash
  @lifetime = params.fetch :lifetime, 60
  super
end

Instance Attribute Details

#lifetimeObject (readonly)

Returns the value of attribute lifetime.



12
13
14
# File 'lib/basiccache/caches/timecache.rb', line 12

def lifetime
  @lifetime
end

Instance Method Details

#[](key = nil) ⇒ Object

Retrieve a value



58
59
60
# File 'lib/basiccache/caches/timecache.rb', line 58

def [](key = nil)
  super.value
end

#cache(key = nil, &code) ⇒ Object

Return a value from the cache, or calculate it and store it Recalculate if the cached value has expired



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/basiccache/caches/timecache.rb', line 34

def cache(key = nil, &code)
  key ||= BasicCache.caller_name
  key = key.to_sym
  if include? key
    @store[key].value
  else
    value = code.call
    @store[key] = TimeCacheItem.new Time.now, value
    value
  end
end

#clear!(key = nil) ⇒ Object

Remove a value, or clear the cache



65
66
67
68
# File 'lib/basiccache/caches/timecache.rb', line 65

def clear!(key = nil)
  resp = super
  resp.class == TimeCacheItem ? resp.value : resp
end

#include?(key = nil) ⇒ Boolean

Check if a value is cached and not expired

Returns:

  • (Boolean)


49
50
51
52
53
# File 'lib/basiccache/caches/timecache.rb', line 49

def include?(key = nil)
  key ||= BasicCache.caller_name
  key = key.to_sym
  @store.include?(key) && Time.now - @store[key].stamp < @lifetime
end

#pruneObject

Prune expired keys



73
74
75
# File 'lib/basiccache/caches/timecache.rb', line 73

def prune
  @store.keys.reject { |k| include? k }.map { |k| clear!(k) && k }
end

#sizeObject

Return the size of the cache (don’t include expired entries)



26
27
28
# File 'lib/basiccache/caches/timecache.rb', line 26

def size
  @store.keys.count { |k| Time.now - @store[k].stamp < @lifetime }
end