63
loading...
This website collects cookies to deliver better user experience
request_store
gem. This is a gem that helps you make per-request “global” storage that doesn’t accidentally leak from one request to the next. For example you could use it to store information about the current user without having to pass it down to every method but without worrying that it will leak into the next request. Globals aren’t exactly the best thing ever, but sometimes they’re practical and you do what you gotta do.request_store
was written to handle web servers that handle each request in its own thread so it stores the per-request data in thread-local storage in Thread.current[:request_store]
. But the problem is, despite its name, Thread.current
is actually fiber-local, not thread-local. So your request handler could store the current user info in the request store, then fire off a new fiber to make an I/O call concurrently, and that fiber won’t have access to the request store.request_store-fibers
gem that detects whenever a new fiber is created by hooking into Fiber.new
. Before the fiber is executed, I copy the current request_store data into a variable. Then as soon as the fiber is resumed the very first time, I copy that data into the fiber's request_store.request_store
with a Rails app that has fibers.request_store-fibers
is actually a thin layer on top of another more generic gem I wrote, fiber_hook
, which does all the magic. It lets you hook into fiber creation and do anything you want right after any fiber is created and before it executes.