Class: Pincerna::Cache
- Inherits:
-
Object
- Object
- Pincerna::Cache
- Defined in:
- lib/pincerna/cache.rb
Overview
A utility class to handle caching.
Constant Summary collapse
- EXPIRATIONS =
Expiration of keys.
{short: 1800, long: 2592000}
- FILE =
Location of the cache file
Pincerna::Base::CACHE_ROOT + "/cache.db"
Instance Attribute Summary collapse
-
#data ⇒ Daybreak::DB
readonly
The cache store.
Class Method Summary collapse
-
.instance ⇒ Object
Returns the instance of the cache.
Instance Method Summary collapse
-
#destroy ⇒ Object
Closes the cache data.
-
#flush ⇒ Object
Flush data into disk.
-
#initialize ⇒ Cache
constructor
Creates a new cache object.
-
#use(key, expiration) ⇒ Object
Use data from cache or fetches new data.
Constructor Details
Instance Attribute Details
#data ⇒ Daybreak::DB (readonly)
Returns The cache store.
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/pincerna/cache.rb', line 12 class Cache # Expiration of keys. EXPIRATIONS = {short: 1800, long: 2592000} # 30 min, 1 month # Location of the cache file FILE = Pincerna::Base::CACHE_ROOT + "/cache.db" attr_reader :data # Returns the instance of the cache. def self.instance @instance ||= Pincerna::Cache.new end # Creates a new cache object. def initialize FileUtils.mkdir_p(File.dirname(FILE)) @data = Daybreak::DB.new(FILE) @flusher = EM.add_periodic_timer(5) { Pincerna::Cache.instance.flush } end # Closes the cache data. def destroy @flusher.cancel @data.close rescue nil end # Flush data into disk. def flush @data.flush @data.compact end # 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. 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 end |
Class Method Details
Instance Method Details
#destroy ⇒ Object
Closes the cache data.
34 35 36 37 |
# File 'lib/pincerna/cache.rb', line 34 def destroy @flusher.cancel @data.close rescue nil end |
#flush ⇒ Object
Flush data into disk.
40 41 42 43 |
# File 'lib/pincerna/cache.rb', line 40 def flush @data.flush @data.compact end |
#use(key, expiration) ⇒ Object
Use data from cache or fetches new data.
49 50 51 52 53 54 55 56 57 58 59 |
# 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 |