[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
2
3
# steveklabnik/request_store: Per-request global storage for Rack.
# https://github.com/steveklabnik/request_store
gem 'request_store', '1.5.0'

Then, run bundle install.

1
$ bundle install

Usages

And try the code to this:

1
2
3
4
5
6
def index
RequestStore.store[:foo] ||= 0
RequestStore.store[:foo] += 1

render :text => RequestStore.store[:foo]
end

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

[1] steveklabnik/request_store: Per-request global storage for Rack. - https://github.com/steveklabnik/request_store

[2] request_store | RubyGems.org | your community gem host - https://rubygems.org/gems/request_store/

[3] madebylotus/request_store-sidekiq: Provides an easy integration between RequestStore and Sidekiq - https://github.com/madebylotus/request_store-sidekiq

[4] request_store-sidekiq | RubyGems.org | your community gem host - https://rubygems.org/gems/request_store-sidekiq

[5] madebylotus/request_store-sidekiq: Provides an easy integration between RequestStore and Sidekiq - https://github.com/madebylotus/request_store-sidekiq