{"id":15412561,"url":"https://github.com/elmassimo/request_store_rails","last_synced_at":"2025-04-06T23:17:35.163Z","repository":{"id":30212168,"uuid":"33763150","full_name":"ElMassimo/request_store_rails","owner":"ElMassimo","description":"📦 Per-request global storage for Rails prepared for multi-threaded apps","archived":false,"fork":false,"pushed_at":"2019-05-20T12:54:13.000Z","size":24,"stargazers_count":83,"open_issues_count":2,"forks_count":6,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-05T00:42:36.377Z","etag":null,"topics":["global-variables","multi-threading","rails","ruby"],"latest_commit_sha":null,"homepage":"https://github.com/ElMassimo/request_store_rails","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ElMassimo.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-04-11T04:53:33.000Z","updated_at":"2024-11-28T16:30:57.000Z","dependencies_parsed_at":"2022-09-05T02:00:15.138Z","dependency_job_id":null,"html_url":"https://github.com/ElMassimo/request_store_rails","commit_stats":null,"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ElMassimo%2Frequest_store_rails","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ElMassimo%2Frequest_store_rails/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ElMassimo%2Frequest_store_rails/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ElMassimo%2Frequest_store_rails/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ElMassimo","download_url":"https://codeload.github.com/ElMassimo/request_store_rails/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247563941,"owners_count":20958971,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["global-variables","multi-threading","rails","ruby"],"created_at":"2024-10-01T16:53:43.879Z","updated_at":"2025-04-06T23:17:35.139Z","avatar_url":"https://github.com/ElMassimo.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"RequestLocals\n=====================\n[![Gem Version](https://badge.fury.io/rb/request_store_rails.svg)](http://badge.fury.io/rb/request_store_rails)\n[![Build Status](https://travis-ci.org/ElMassimo/request_store_rails.svg)](https://travis-ci.org/ElMassimo/request_store_rails)\n[![Test Coverage](https://codeclimate.com/github/ElMassimo/request_store_rails/badges/coverage.svg)](https://codeclimate.com/github/ElMassimo/request_store_rails)\n[![Code Climate](https://codeclimate.com/github/ElMassimo/request_store_rails/badges/gpa.svg)](https://codeclimate.com/github/ElMassimo/request_store_rails)\n[![Inline docs](http://inch-ci.org/github/ElMassimo/request_store_rails.svg)](http://inch-ci.org/github/ElMassimo/request_store_rails)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ElMassimo/request_store_rails/blob/master/LICENSE.txt)\n\nIf you have ever needed to use a global variable in Rails, you know it sucks.\n\nOne of the usual tricks is to go for `Thread.current`, or if you have done your\nhomework, to use the awesome [`request_store`](https://github.com/steveklabnik/request_store).\n\n```ruby\n# Using Thread.current\ndef self.foo\n  Thread.current[:foo] ||= 0\nend\n\ndef self.foo=(value)\n  Thread.current[:foo] = value\nend\n\n# Using RequestStore\ndef self.foo\n  RequestStore.fetch(:foo) { 0 }\nend\n\ndef self.foo=(value)\n  RequestStore.store[:foo] = value\nend\n```\n\n### The problem\n\n- Using `Thread.current`, values can stick around even after the request is over,\nsince some servers have a pool of Threads that they reuse, which [can cause bugs](https://github.com/steveklabnik/request_store#the-problem).\n\n- Using `request_store`, the storage is _*not actually*_ request local. Variables\nare stored in `Thread.current`, except that the storage is cleared after each\nrequest. However, this does not work when you need to use multiple threads per\nrequest, _different_ threads access _different_ stores.\n\n### The solution\n\nAdd this line to your Gemfile:\n\n```ruby\ngem 'request_store_rails'\n```\n\nAnd change the code to this:\n\n```ruby\ndef self.foo\n  RequestLocals.fetch(:foo) { 0 }\nend\n\ndef self.foo=(value)\n  RequestLocals.store[:foo] = value\nend\n```\n\nOh yeah, everywhere you used `Thread.current` or `RequestStore.store` just\nchange it to `RequestLocals.store`. Now your variables will actually be stored\nin a true _request-local_ way.\n\n### No Rails? No Problem!\n\nA Railtie is added that configures the Middleware for you, but if you're not\nusing Rails, no biggie! Just use the Middleware yourself, however you need.\nYou'll probably have to shove this somewhere:\n\n```ruby\nuse RequestStoreRails::Middleware\n```\n\n## Multi-Threading\nThe middleware in the gem sets a thread-local variable `:request_store_id` in\n`Thread.current` for the main thread that is executing the request.\n\nIf you need to spawn threads within a server that is already using thread-based\nconcurrency, all you need to do is to make sure that the `:request_store_id`\nvariable is set for your threads, and you will be able to access the\n`RequestLocals` as usual.\n\nA good way to apply this pattern is by encapsulating it into a helper class:\n\n```ruby\n# Public: Custom thread class that allows us to preserve the request context.\nclass ThreadWithContext\n\n  # Public: Returns a new Thread that preserves the context of the current request.\n  def ThreadWithContext.new(*args)\n    store_id = RequestLocals.current_store_id\n    Thread.new {\n      RequestLocals.set_current_store_id(store_id)\n      yield *args\n    }\n  end\nend\n\nRequestLocals[:foo] = 1\n\nThreadWithContext.new {\n  puts RequestLocals[:foo] # =\u003e 1\n}\n```\nThe gem does not provide such construct to avoid name collisions, you are free\nto reuse the snippet above and adjust it to match your use case.\n\nIf you are feeling adventurous, you could try using this [fire and forget script](https://gist.github.com/ElMassimo/e2f99848db6a415f1aaa) and make all of your threads request aware, or\nshould I say _prepend and forget_ :smile:? Probably not something to be used in\na production environment, but whatever floats your boat :boat:\n\n### Atomicity\nHave in mind that the `RequestLocals.fetch(:foo) { 'default' }` operation is\n[atomic](https://github.com/ElMassimo/request_store_rails/blob/master/lib/request_locals.rb#L62),\nwhile `RequestLocal[:foo] ||= 'default'` is not. In most scenarios, there is not\na lot of difference, but if you are in a concurrent environment make sure to\nuse the one that is more suitable for your use case :wink:\n\n## Replacing `request_store`\nWhile the plan is not to achieve 100% compatibility, this gem usually works well\nas a drop-in replacement. If you are using gems that rely on `RequestStore` but\nfor some reason you need them to use the appropriate request/thread scope, you\ncan try something like this on `application.rb` or similar:3\n```ruby\nif RequestStore != RequestLocals\n  RequestStore::Railtie.initializers.clear\n  Kernel.suppress_warnings { RequestStore = RequestLocals }\nend\n```\n\n## Usage in Sidekiq\nIf your code depends on these global variables, it's likely that you'll need\nto avoid collisions in Sidekiq workers (which would happen if the current store\nid is `nil`).\n\nYou can use the following middleware, using the job id to identify the store:\n\n```ruby\nclass Sidekiq::Middleware::Server::RequestStoreRails\n  def call(_worker, job, _queue)\n    RequestLocals.set_current_store_id(job['jid'])\n    yield\n  ensure\n    RequestLocals.clear!\n    RequestLocals.set_current_store_id(nil)\n  end\nend\n```\n\nMake sure to configure it as server middleware:\n\n```ruby\nSidekiq.configure_server do |config|\n  config.server_middleware do |chain|\n    chain.add Sidekiq::Middleware::Server::RequestStoreRails\n  end\nend\n```\n\n## Special Thanks\nThe inspiration for this gem, tests, and a big part of the readme were borrowed\nfrom the really cool [`request_store`](https://github.com/steveklabnik/request_store) gem.\nThanks [Steve](https://github.com/steveklabnik) :smiley:\n\n## Contributing\n\n1. Fork it\n2. Create your feature branch (`git checkout -b my-new-feature`)\n3. Commit your changes (`git commit -am 'Add some feature'`)\n4. Push to the branch (`git push origin my-new-feature`)\n5. Create new Pull Request\n\nDon't forget to run the tests with `rake`.\n\nLicense\n--------\n\n    Copyright (c) 2015 Máximo Mussini\n\n    Permission is hereby granted, free of charge, to any person obtaining\n    a copy of this software and associated documentation files (the\n    \"Software\"), to deal in the Software without restriction, including\n    without limitation the rights to use, copy, modify, merge, publish,\n    distribute, sublicense, and/or sell copies of the Software, and to\n    permit persons to whom the Software is furnished to do so, subject to\n    the following conditions:\n\n    The above copyright notice and this permission notice shall be\n    included in all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felmassimo%2Frequest_store_rails","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Felmassimo%2Frequest_store_rails","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felmassimo%2Frequest_store_rails/lists"}