Class: Kameleoon::Storage::CacheImpl

Inherits:
Cache
  • Object
show all
Defined in:
lib/kameleoon/storage/cache.rb

Overview

Implementation of Cache with auto cleaning feature

Instance Method Summary collapse

Constructor Details

#initialize(expiration_time, cleaning_interval) ⇒ CacheImpl

Returns a new instance of CacheImpl.



25
26
27
28
29
30
31
# File 'lib/kameleoon/storage/cache.rb', line 25

def initialize(expiration_time, cleaning_interval)
  super()
  @mutex = Mutex.new
  @expiration_time = expiration_time
  @cleaning_interval = cleaning_interval
  @cache = {}
end

Instance Method Details

#active_itemsObject



48
49
50
51
52
53
54
55
# File 'lib/kameleoon/storage/cache.rb', line 48

def active_items
  active_items = {}
  remove_expired_entries
  @mutex.synchronize do
    @cache.each_pair { |key, entry| active_items[key] = entry[:value] }
  end
  active_items
end

#get(key) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/kameleoon/storage/cache.rb', line 40

def get(key)
  entry = @cache[key]
  return entry[:value] unless entry.nil? || expired?(entry)

  @mutex.synchronize { @cache.delete(key) }
  nil
end

#set(key, value) ⇒ Object



33
34
35
36
37
38
# File 'lib/kameleoon/storage/cache.rb', line 33

def set(key, value)
  @mutex.synchronize do
    start_cleaner_timer if @cleaning_interval.positive? && @cleaner_timer.nil?
    @cache[key] = { value: value, expired: Time.now + @expiration_time }
  end
end