Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Fiber#storage
static VALUE
rb_fiber_storage_get(VALUE self)
{
storage_access_must_be_from_same_fiber(self);
VALUE storage = fiber_storage_get(fiber_ptr(self), FALSE);
if (storage == Qnil) {
return Qnil;
}
else {
return rb_obj_dup(storage);
}
}
Returns a copy of the storage hash for the fiber. The method can only be called on the Fiber.current.
Ruby version changes
-
3.2
-
Introduce
Fiber.[]andFiber.[]=for inheritable fiber storage. IntroduceFiber#storageandFiber#storage=(experimental) for getting and resetting the current storage. IntroduceFiber.new(storage:)for setting the storage when creating a fiber. [Feature #19078]Existing
ThreadandFiberlocal variables can be tricky to use. Thread-local variables are shared between all fibers, making it hard to isolate, while Fiber-local variables can be hard to share. It is often desirable to define unit of execution (“execution context”) such that some state is shared between all fibers and threads created in that context. This is whatFiberstorage provides.Exampledef log(message) puts "#{Fiber[:request_id]}: #{message}" end def handle_requests while request = read_request Fiber.schedule do Fiber[:request_id] = SecureRandom.uuid request.messages.each do |message| Fiber.schedule do log("Handling #{message}") # Log includes inherited request_id. end end end end end
You should generally consider
Fiberstorage for any state which you want to be shared implicitly between all fibers and threads created in a given context, e.g. a connection pool, a request id, a logger level, environment variables, configuration, etc.
-