Class: Cosmo::Utils::TTLCache

Inherits:
Object
  • Object
show all
Defined in:
lib/cosmo/utils/ttl_cache.rb,
sig/cosmo/utils/ttl_cache.rbs

Instance Method Summary collapse

Constructor Details

#initializeTTLCache

Returns a new instance of TTLCache.



6
7
8
# File 'lib/cosmo/utils/ttl_cache.rb', line 6

def initialize
  @store = {}
end

Instance Method Details

#fetch(key, ttl: nil) { ... } ⇒ Object

Parameters:

  • key (Object)
  • ttl: (Numeric, nil) (defaults to: nil)

Yields:

Yield Returns:

  • (Object)

Returns:

  • (Object)


21
22
23
24
25
26
27
# File 'lib/cosmo/utils/ttl_cache.rb', line 21

def fetch(key, ttl: nil)
  return get(key) if key?(key)

  result = yield
  set(key, result, ttl: ttl)
  result
end

#get(key) ⇒ Object

Parameters:

  • key (Object)

Returns:

  • (Object)


15
16
17
18
19
# File 'lib/cosmo/utils/ttl_cache.rb', line 15

def get(key)
  return unless key?(key)

  @store[key].first
end

#key?(key) ⇒ Boolean

Parameters:

  • key (Object)

Returns:

  • (Boolean)


31
32
33
34
35
36
37
38
39
40
41
# File 'lib/cosmo/utils/ttl_cache.rb', line 31

def key?(key)
  exists = @store.key?(key)
  return false unless exists

  _, ttl = @store[key]
  return true unless ttl
  return true if Time.now < ttl

  @store.delete(key)
  false
end

#set(key, value, ttl: nil) ⇒ Object

Parameters:

  • key (Object)
  • value (Object)
  • ttl: (Numeric, nil) (defaults to: nil)

Returns:

  • (Object)


10
11
12
13
# File 'lib/cosmo/utils/ttl_cache.rb', line 10

def set(key, value, ttl: nil)
  @store[key] = [value, ttl ? Time.now + ttl : nil]
  value
end