Class: Rack::Component::MemoryCache

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/component/memory_cache.rb

Overview

A threadsafe, in-memory, per-component cache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(length: 100) ⇒ MemoryCache

Use a hash to store cached calls and a mutex to make it threadsafe



8
9
10
11
12
# File 'lib/rack/component/memory_cache.rb', line 8

def initialize(length: 100)
  @store = {}
  @length = length
  @mutex = Mutex.new
end

Instance Attribute Details

#mutexObject (readonly)

Returns the value of attribute mutex.



5
6
7
# File 'lib/rack/component/memory_cache.rb', line 5

def mutex
  @mutex
end

#storeObject (readonly)

Returns the value of attribute store.



5
6
7
# File 'lib/rack/component/memory_cache.rb', line 5

def store
  @store
end

Instance Method Details

#fetch(key) ⇒ Object

Fetch a key from the cache, if it exists If the key doesn’t exist and a block is passed, set the key

Returns:

  • the cached value



17
18
19
20
21
# File 'lib/rack/component/memory_cache.rb', line 17

def fetch(key)
  store.fetch(key) do
    set(key, yield) if block_given?
  end
end

#flushHash

Empty the cache

Returns:

  • (Hash)

    the empty store



25
26
27
# File 'lib/rack/component/memory_cache.rb', line 25

def flush
  mutex.synchronize { @store = {} }
end