Class: SqAuth::SqAuthCache

Inherits:
Object
  • Object
show all
Defined in:
lib/sq_auth/sq_auth_cache.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{:ttl => 600, :max_fetches => 1000}

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ SqAuthCache

Returns a new instance of SqAuthCache.



4
5
6
7
8
9
10
# File 'lib/sq_auth/sq_auth_cache.rb', line 4

def initialize options = {}
  options = DEFAULT_OPTIONS.merge(options)
  @cache = {}
  @ttl = options[:ttl]
  @max_fetches = options[:max_fetches]
  @keys_access = Hash.new{|h,k| h[k] = {updated_at: Time.now, fetches: 0}}
end

Instance Method Details

#clear_cache_key(key) ⇒ Object



24
25
26
27
# File 'lib/sq_auth/sq_auth_cache.rb', line 24

def clear_cache_key key
  @cache.delete(key)
  @keys_access.delete(key)
end

#fetch(key) ⇒ Object



12
13
14
15
16
# File 'lib/sq_auth/sq_auth_cache.rb', line 12

def fetch key
  secure_cache_operation(key) do
    @cache[key]
  end
end

#save(key, value) ⇒ Object



18
19
20
21
22
# File 'lib/sq_auth/sq_auth_cache.rb', line 18

def save key, value
  clear_cache_key(key)
  @cache[key] = value
  @keys_access[key]
end

#secure_cache_operation(key, &block) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/sq_auth/sq_auth_cache.rb', line 29

def secure_cache_operation key, &block
  @keys_access[key][:fetches] += 1
  key_age = (Time.now - @keys_access[key][:updated_at]).to_i
  fetches = @keys_access[key][:fetches]
  if key_age > @ttl || fetches > @max_fetches || key_age < 0
    clear_cache_key(key)
  end
  yield if block_given?
end