class BasicCache::TimeCache

Time-based cache object

Attributes

lifetime[R]

Public Class Methods

new(params = {}) click to toggle source

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

Calls superclass method BasicCache::Cache::new
# 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

Public Instance Methods

[](key = nil) click to toggle source

Retrieve a value

Calls superclass method BasicCache::Cache#[]
# File lib/basiccache/caches/timecache.rb, line 58
def [](key = nil)
  super.value
end
cache(key = nil, &code) click to toggle source

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

# 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) click to toggle source

Remove a value, or clear the cache

Calls superclass method BasicCache::Cache#clear!
# File lib/basiccache/caches/timecache.rb, line 65
def clear!(key = nil)
  resp = super
  resp.class == TimeCacheItem ? resp.value : resp
end
include?(key = nil) click to toggle source

Check if a value is cached and not expired

# 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
prune() click to toggle source

Prune expired keys

# File lib/basiccache/caches/timecache.rb, line 73
def prune
  @store.keys.reject { |k| include? k }.map { |k| clear!(k) && k }
end
size() click to toggle source

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

# File lib/basiccache/caches/timecache.rb, line 26
def size
  @store.keys.count { |k| Time.now - @store[k].stamp < @lifetime }
end