Class: BluntCache

Inherits:
Object
  • Object
show all
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

Class Method Details

.dataObject



44
45
46
# File 'lib/blunt-cache.rb', line 44

def self.data
  @data||= {}
end

.expire_defaultObject



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, options = {}, &block)
  expire = options[:expire]
  if self.key?(key)
    self.data[key]
  else
    result = block.call
    self.set key, result, :expire => expire
    result
  end
end

.flushObject

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.timestamp[key].is_a?(Time) && Time.now < self.timestamp[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.

Returns:

  • (Boolean)


21
22
23
# File 'lib/blunt-cache.rb', line 21

def self.key?(key)
  self.data.key?(key) && self.timestamp[key].is_a?(Time) && Time.now < self.timestamp[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, options = {})
  expire = options[:expire]
  self.timestamp[key] = Time.now + (expire || self.expire_default)
  self.data[key] = data
  data
end

.timestampObject



48
49
50
# File 'lib/blunt-cache.rb', line 48

def self.timestamp
  @timestamp||= {}
end