Class: TypedCache::Backends::Memory

Inherits:
Object
  • Object
show all
Includes:
TypedCache::Backend
Defined in:
lib/typed_cache/backends/memory.rb

Overview

A type-safe memory store implementation with built-in namespacing

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from TypedCache::Backend

#fetch_multi, #read_multi, #write_multi

Constructor Details

#initialize(ttl: 600) ⇒ Memory

: (ttl: Integer) -> void



52
53
54
55
# File 'lib/typed_cache/backends/memory.rb', line 52

def initialize(ttl: 600)
  @ttl = ttl
  @backing_store = Concurrent::Map.new
end

Instance Attribute Details

#backing_storeObject (readonly)

: hash_like[String, Entry]



49
50
51
# File 'lib/typed_cache/backends/memory.rb', line 49

def backing_store
  @backing_store
end

#ttlObject (readonly)

: Integer



48
49
50
# File 'lib/typed_cache/backends/memory.rb', line 48

def ttl
  @ttl
end

Instance Method Details

#clearObject

: -> void



92
93
94
# File 'lib/typed_cache/backends/memory.rb', line 92

def clear
  backing_store.clear
end

#delete(key) ⇒ Object

: (cache_key) -> V?



76
77
78
79
# File 'lib/typed_cache/backends/memory.rb', line 76

def delete(key)
  entry = backing_store.delete(key)
  entry&.value
end

#fetch(key, ttl: @ttl, **opts, &block) ⇒ Object

: (cache_key, ttl: Integer, **top) { () -> V? } -> V?



98
99
100
101
102
103
104
105
# File 'lib/typed_cache/backends/memory.rb', line 98

def fetch(key, ttl: @ttl, **opts, &block)
  purge_expired_keys
  result = backing_store.compute_if_absent(key) do
    Entry.new(value: yield(key), expires_at: Clock.now + ttl)
  end

  result.value
end

#key?(key) ⇒ Boolean

: (cache_key) -> bool

Returns:

  • (Boolean)


83
84
85
86
87
88
# File 'lib/typed_cache/backends/memory.rb', line 83

def key?(key)
  return false unless backing_store.key?(key)

  entry = backing_store[key]
  !entry.expired?
end

#read(key, **kwargs) ⇒ Object

: (cache_key, **top) -> V?



59
60
61
62
63
64
# File 'lib/typed_cache/backends/memory.rb', line 59

def read(key, **kwargs)
  purge_expired_keys

  entry = backing_store[key]
  entry&.value
end

#write(key, value, expires_in: @ttl, expires_at: Clock.now + expires_in, **kwargs) ⇒ Object

: (cache_key, V, expires_in: Integer, expires_at: Time, **top) -> V



68
69
70
71
72
# File 'lib/typed_cache/backends/memory.rb', line 68

def write(key, value, expires_in: @ttl, expires_at: Clock.now + expires_in, **kwargs)
  entry = Entry.new(value: value, expires_at: expires_at)
  backing_store[key] = entry
  value
end