Class: RequestLocals

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Singleton
Defined in:
lib/request_locals.rb

Overview

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.

Defined Under Namespace

Classes: Cache

Constant Summary collapse

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.

:request_store_id

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRequestLocals

Returns a new instance of RequestLocals.



45
46
47
# File 'lib/request_locals.rb', line 45

def initialize
  @cache = Cache.new
end

Class Method Details

.set_current_store_id(id) ⇒ Object

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



91
92
93
# File 'lib/request_locals.rb', line 91

def self.set_current_store_id(id)
  Thread.current[REQUEST_STORE_ID] = id
end

Instance Method Details

#clear!Object

Public: Removes all the request-local variables.

Returns nothing.



52
53
54
# File 'lib/request_locals.rb', line 52

def clear!
  @cache.delete(current_store_id)
end

#clear_all!Object

Public: Clears all the request-local variable stores.

Returns nothing.



59
60
61
# File 'lib/request_locals.rb', line 59

def clear_all!
  @cache = Cache.new
end

#current_store_idObject

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`.



86
87
88
# File 'lib/request_locals.rb', line 86

def current_store_id
  Thread.current[REQUEST_STORE_ID]
end

#exist?(key) ⇒ Boolean Also known as: key?

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

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

Returns:

  • (Boolean)


66
67
68
# File 'lib/request_locals.rb', line 66

def exist?(key)
  store.key?(key)
end

#fetch(key, &block) ⇒ Object

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.



78
79
80
# File 'lib/request_locals.rb', line 78

def fetch(key, &block)
  store.compute_if_absent(key, &block)
end