[Awesome Ruby Gem] Use request_store gem to store pre request global data
request_store
request_store
gives you per-request global storage.
Using request_store
, the variables are stored in Thread.current
, and that the storage is cleared after each request.
Installation
You can install it as a gem:
1 | gem install request_store |
or add it into a Gemfile (Bundler):
1 | # steveklabnik/request_store: Per-request global storage for Rack. |
Then, run bundle install
.
1 | bundle install |
Usages
And try the code to this:
1 | def index |
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.
References
[2] request_store | RubyGems.org | your community gem host - https://rubygems.org/gems/request_store/