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.1.0"

Class Method Summary collapse

Class Method Details

.dataObject



35
36
37
# File 'lib/blunt_cache.rb', line 35

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

.expire_defaultObject



43
44
45
# File 'lib/blunt_cache.rb', line 43

def self.expire_default
  @expire_default||=60
end

.fetch(key, expire: nil, &block) ⇒ Object

Get key from cache. Executes block, stores it’s result and returns it if not set or expired.



18
19
20
21
22
23
24
25
# File 'lib/blunt_cache.rb', line 18

def self.fetch(key, expire: nil, &block)
  result = self.get key
  if result.nil?
    self.set key, block.call, expire: expire
  else
    result
  end
end

.flushObject

Clear cache



28
29
30
31
# File 'lib/blunt_cache.rb', line 28

def self.flush
  @data = {}
  @timestamp = {}
end

.get(key) ⇒ Object

Get key from cache. Returns nil if not set or expired.



13
14
15
# File 'lib/blunt_cache.rb', line 13

def self.get(key)
  self.timestamp[key].is_a?(Time) && Time.now < self.timestamp[key] ? self.data[key] : nil
end

.set(key, data, expire: nil) ⇒ Object

Store data in cache by key for :expire seconds (default is 60 sec)



6
7
8
9
10
# File 'lib/blunt_cache.rb', line 6

def self.set(key, data, expire: nil)
  self.timestamp[key] = Time.now + (expire || self.expire_default)
  self.data[key] = data
  data
end

.timestampObject



39
40
41
# File 'lib/blunt_cache.rb', line 39

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