Class: BluntCache
- Inherits:
-
Object
- Object
- BluntCache
- Defined in:
- lib/blunt-cache.rb,
lib/blunt-cache/version.rb
Overview
In-memory cache service.
Constant Summary collapse
- VERSION =
"0.2.0"
Class Method Summary collapse
- .data ⇒ Object
- .expire_default ⇒ Object
-
.fetch(key, options = {}, &block) ⇒ Object
Get
key
from cache. -
.flush ⇒ Object
Clear cache.
-
.get(key) ⇒ Object
Get
key
from cache. -
.key?(key) ⇒ Boolean
Checks if key present in store.
-
.set(key, data, options = {}) ⇒ Object
Store
data
in cache bykey
for:expire
seconds (default is 60 sec) def self.set(key, data, expire: nil). - .timestamp ⇒ Object
Class Method Details
.data ⇒ Object
44 45 46 |
# File 'lib/blunt-cache.rb', line 44 def self.data @data||= {} end |
.expire_default ⇒ Object
52 53 54 |
# File 'lib/blunt-cache.rb', line 52 def self.expire_default @expire_default||=60 end |
.fetch(key, options = {}, &block) ⇒ Object
Get key
from cache. Executes block
, stores it’s result and returns it if not set or expired.
def self.fetch(key, expire: nil, &block)
27 28 29 30 31 32 33 34 35 36 |
# File 'lib/blunt-cache.rb', line 27 def self.fetch(key, = {}, &block) expire = [:expire] if self.key?(key) self.data[key] else result = block.call self.set key, result, :expire => expire result end end |
.flush ⇒ Object
Clear cache
39 40 41 42 |
# File 'lib/blunt-cache.rb', line 39 def self.flush @data = {} @timestamp = {} end |
.get(key) ⇒ Object
Get key
from cache. Returns nil if not set or expired.
15 16 17 |
# File 'lib/blunt-cache.rb', line 15 def self.get(key) self.[key].is_a?(Time) && Time.now < self.[key] ? self.data[key] : nil end |
.key?(key) ⇒ Boolean
Checks if key present in store. Returns true if key exists (even if value is false or nil) and false if key doesn’t exist or expired.
21 22 23 |
# File 'lib/blunt-cache.rb', line 21 def self.key?(key) self.data.key?(key) && self.[key].is_a?(Time) && Time.now < self.[key] end |
.set(key, data, options = {}) ⇒ Object
Store data
in cache by key
for :expire
seconds (default is 60 sec)
def self.set(key, data, expire: nil)
7 8 9 10 11 12 |
# File 'lib/blunt-cache.rb', line 7 def self.set(key, data, = {}) expire = [:expire] self.[key] = Time.now + (expire || self.expire_default) self.data[key] = data data end |
.timestamp ⇒ Object
48 49 50 |
# File 'lib/blunt-cache.rb', line 48 def self. @timestamp||= {} end |