request_store gives you per-request global storage.
request_store, the variables are stored in
Thread.current, and that the storage is cleared after each request.
You can install it as a gem:
gem install request_store
or add it into a Gemfile (Bundler):
# steveklabnik/request_store: Per-request global storage for Rack.
And try the code to this:
Now no matter what server you use, you’ll get 1 every time: the storage is local to that request.
Using with Sidekiq
This gem uses a Rack middleware to clear the store object after every request, but that doesn’t translate well to background processing with Sidekiq.
A companion library, madebylotus/request_store-sidekiq: Provides an easy integration between RequestStore and Sidekiq - https://github.com/madebylotus/request_store-sidekiq creates a Sidekiq middleware that will ensure the store is cleared after each job is processed, for security and consistency with how this is done in Rack.
Using with multiple threads per request
request_store does not work when you need to use multiple threads per request, different threads access different stores. madebylotus/request_store-sidekiq: Provides an easy integration between RequestStore and Sidekiq - https://github.com/madebylotus/request_store-sidekiq may be a good alternative gem.