class Rack::Component::MemoryCache
A threadsafe, in-memory, per-component cache
Attributes
mutex[R]
store[R]
Public Class Methods
new(length: 100)
click to toggle source
Use a hash to store cached calls and a mutex to make it threadsafe
# File lib/rack/component/memory_cache.rb, line 8 def initialize(length: 100) @store = {} @length = length @mutex = Mutex.new end
Public Instance Methods
fetch(key) { || ... }
click to toggle source
Fetch a key from the cache, if it exists If the key doesn't exist and a block is passed, set the key @return the cached value
# File lib/rack/component/memory_cache.rb, line 17 def fetch(key) store.fetch(key) do set(key, yield) if block_given? end end
flush()
click to toggle source
Empty the cache @return [Hash] the empty store
# File lib/rack/component/memory_cache.rb, line 25 def flush mutex.synchronize { @store = {} } end
Private Instance Methods
set(key, value)
click to toggle source
Cache a value and return it
# File lib/rack/component/memory_cache.rb, line 32 def set(key, value) mutex.synchronize do store[key] = value store.delete(@store.keys.first) if store.length > @length value end end