class Pincerna::Cache
A utility class to handle caching.
@attribute [r] data
@return [Daybreak::DB] The cache store.
Constants
- EXPIRATIONS
Expiration of keys.
- FILE
Location of the cache file
Attributes
data[R]
Public Class Methods
instance()
click to toggle source
Returns the instance of the cache.
# File lib/pincerna/cache.rb, line 22 def self.instance @instance ||= Pincerna::Cache.new end
new()
click to toggle source
Creates a new cache object.
# File lib/pincerna/cache.rb, line 27 def initialize FileUtils.mkdir_p(File.dirname(FILE)) @data = Daybreak::DB.new(FILE) @flusher = EM.add_periodic_timer(5) { Pincerna::Cache.instance.flush } end
Public Instance Methods
destroy()
click to toggle source
Closes the cache data.
# File lib/pincerna/cache.rb, line 34 def destroy @flusher.cancel @data.close rescue nil end
flush()
click to toggle source
Flush data into disk.
# File lib/pincerna/cache.rb, line 40 def flush @data.flush @data.compact end
use(key, expiration) { || ... }
click to toggle source
Use data from cache or fetches new data.
@param key [String] The key of the data. @param expiration [Fixnum] Expiration of new data, in seconds.
# File lib/pincerna/cache.rb, line 49 def use(key, expiration) value = @data[key] if !value || Time.now.to_f > value[:expiration] then data = yield @data[key] = {data: data, expiration: Time.now.to_f + expiration} data else value[:data] end end