Class: MatrixSdk::Util::TinycacheAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/matrix_sdk/util/tinycache_adapter.rb

Defined Under Namespace

Classes: Value

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTinycacheAdapter

Returns a new instance of TinycacheAdapter.



7
8
9
10
11
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 7

def initialize
  @config = {}

  clear
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



5
6
7
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 5

def client
  @client
end

#configObject

Returns the value of attribute config.



5
6
7
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 5

def config
  @config
end

Instance Method Details

#cleanupObject



61
62
63
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 61

def cleanup
  @cache.delete_if { |_, v| v.expired? }
end

#clearObject



57
58
59
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 57

def clear
  @cache = {}
end

#delete(key) ⇒ Object



50
51
52
53
54
55
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 50

def delete(key)
  return false unless exist?(key)

  cache.delete key
  true
end

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 30

def exist?(key)
  cache.key?(key)
end

#fetch(key, expires_in: nil, cache_level: nil, **_opts) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 38

def fetch(key, expires_in: nil, cache_level: nil, **_opts)
  expires_in ||= config.dig(key, :expires)
  cache_level ||= client&.cache
  cache_level ||= :all
  cache_level = Tinycache::CACHE_LEVELS[cache_level]

  return read(key) if exist?(key) && !cache[key].expired?

  value = yield
  write(key, value, expires_in: expires_in, cache_level: cache_level)
end

#read(key) ⇒ Object



13
14
15
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 13

def read(key)
  cache[key]&.value
end

#valid?(key) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 34

def valid?(key)
  exist?(key) && !cache[key].expired?
end

#write(key, value, expires_in: nil, cache_level: nil) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/matrix_sdk/util/tinycache_adapter.rb', line 17

def write(key, value, expires_in: nil, cache_level: nil)
  expires_in ||= config.dig(key, :expires)
  expires_in ||= 24 * 60 * 60
  cache_level ||= client&.cache
  cache_level ||= :all
  cache_level = Tinycache::CACHE_LEVELS[cache_level] unless cache_level.is_a? Integer

  return value if cache_level < Tinycache::CACHE_LEVELS[config.dig(key, :level) || :none]

  cache[key] = Value.new(value, Time.now, Time.now + expires_in)
  value
end