Skip to content
instance method · added in Ruby 3.2

Fiber#storage=

(::Hash[::interned, untyped]) -> ::Hash[::interned, untyped]
fiber.storage = hash

Sets the storage hash for the fiber. This feature is experimental and may change in the future. The method can only be called on the Fiber.current.

You should be careful about using this method as you may inadvertently clear important fiber-storage state. You should mostly prefer to assign specific keys in the storage using Fiber::[]=.

You can also use Fiber.new(storage: nil) to create a fiber with an empty storage.

Example:

Example
while request = request_queue.pop
  # Reset the per-request state:
  Fiber.current.storage = nil
  handle_request(request)
end

Ruby version changes

  1. 3.2
    • Introduce Fiber.[] and Fiber.[]= for inheritable fiber storage. Introduce Fiber#storage and Fiber#storage= (experimental) for getting and resetting the current storage. Introduce Fiber.new(storage:) for setting the storage when creating a fiber. [Feature #19078]

      Existing Thread and Fiber local 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 what Fiber storage provides.

      Example
      def 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 Fiber storage 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.

See also #storage #to_s #resume #transfer also in 4.1 · 3.4 · 3.3 · 3.2