class RequestLocals

Public: Provides per-request global storage, by offering an interface that is very similar to Rails.cache, or Hash.

The store may be shared between threads, as long as the current store id is set as a thread-local variable.

Intended to work in collaboration with the RequestStoreRails middleware, that will clear the request local variables after each request.

Constants

REQUEST_STORE_ID

Internal: The key of the thread-local variable the library uses to store the identifier of the current store, used during the request lifecycle.

Public Class Methods

new() click to toggle source
# File lib/request_locals.rb, line 45
def initialize
  @cache = Cache.new
end
set_current_store_id(id) click to toggle source

Public: Changes the store RequestLocals will read from in the current thread.

# File lib/request_locals.rb, line 91
def self.set_current_store_id(id)
  Thread.current[REQUEST_STORE_ID] = id
end

Public Instance Methods

clear!() click to toggle source

Public: Removes all the request-local variables.

Returns nothing.

# File lib/request_locals.rb, line 52
def clear!
  @cache.delete(current_store_id)
end
clear_all!() click to toggle source

Public: Clears all the request-local variable stores.

Returns nothing.

# File lib/request_locals.rb, line 59
def clear_all!
  @cache = Cache.new
end
current_store_id() click to toggle source

Public: The current request is inferred from the current thread.

NOTE: It's very important to set the current store id when spawning new threads within a single request, using `RequestLocals.set_current_store_id`.

# File lib/request_locals.rb, line 86
def current_store_id
  Thread.current[REQUEST_STORE_ID]
end
exist?(key) click to toggle source

Public: Checks if a value was stored for the given key.

Returns true if there is a value stored for the key.

# File lib/request_locals.rb, line 66
def exist?(key)
  store.key?(key)
end
Also aliased as: key?
fetch(key, &block) click to toggle source

Public: Implements fetch in a consistent way with Rails.cache, persisting the value yielded by the block if the key was not found.

Returns an existing value for the key is found, otherwise it returns the value yielded by the block.

# File lib/request_locals.rb, line 78
def fetch(key, &block)
  store.compute_if_absent(key, &block)
end
key?(key)

Public: Alias to exist?

Alias for: exist?

Protected Instance Methods

new_store() click to toggle source

Internal: Returns a new empty structure where the request-local variables will be stored.

# File lib/request_locals.rb, line 107
def new_store
  Cache.new
end
store() click to toggle source

Internal: Returns the structure that holds the request-local variables for the current request.

Returns a ThreadSafe::Cache.

# File lib/request_locals.rb, line 101
def store
  @cache.compute_if_absent(current_store_id) { new_store }
end