Class: Resterl::Caches::SimpleCache

Inherits:
CacheInterface show all
Defined in:
lib/resterl/caches/simple_cache.rb

Defined Under Namespace

Classes: Entry

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ SimpleCache

Returns a new instance of SimpleCache.



13
14
15
16
17
18
19
20
# File 'lib/resterl/caches/simple_cache.rb', line 13

def initialize options = {}
  @options = {
    expiration_check_interval: 1_000,
    cache_key_prefix: 'RESTERL_'
  }.merge options
  @expiration_check_counter = 0
  @data = {}
end

Instance Method Details

#delete(key) ⇒ Object



56
57
58
59
60
# File 'lib/resterl/caches/simple_cache.rb', line 56

def delete key
  key = internal_key key

  @data.delete key
end

#flushObject



62
63
64
# File 'lib/resterl/caches/simple_cache.rb', line 62

def flush
  @data = {}
end

#read(key) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/resterl/caches/simple_cache.rb', line 22

def read key
  key = internal_key key

  do_expiration_check
  entry = @data[key]

  # return if nothing in cache
  return nil unless entry

  # entry expired?
  if verify_entry_not_expired(key, entry)
    entry.data
  else
    nil
  end
end

#write(key, value, expires_in = nil) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/resterl/caches/simple_cache.rb', line 39

def write key, value, expires_in = nil
  key = internal_key key

  do_expiration_check

  # calculate expiration
  expires_at = Time.now + expires_in.to_i if expires_in.to_i > 0

  # store data
  if expires_at.nil? || expires_at > Time.now
    entry = Entry.new(value, expires_at)
    @data[key] = entry
  end

  value
end