Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
Fiber.[]
static VALUE
rb_fiber_storage_aref(VALUE class, VALUE key)
{
key = rb_to_symbol(key);
VALUE storage = fiber_storage_get(fiber_current(), FALSE);
if (storage == Qnil) return Qnil;
return rb_hash_aref(storage, key);
}
Returns the value of the fiber storage variable identified by key.
The key must be a symbol, and the value is set by Fiber#[]= or Fiber#store.
See also Fiber::[]=.
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.
-