Method: Mongoid::Threaded#get

Defined in:
lib/mongoid/threaded.rb

#get(key, &default) ⇒ Object | nil

Queries the thread- or fiber-local variable with the given name. If a block is given, and the variable does not already exist, the return value of the block will be set as the value of the variable before returning it.

It is very important that applications (and especially Mongoid) use this method instead of Thread#[], since Thread#[] is actually for fiber-local variables, and Mongoid uses Fibers as an implementation detail in some callbacks. Putting thread-local state in a fiber-local store will result in the state being invisible when relevant callbacks are run in a different fiber.

Affected callbacks are cascading callbacks on embedded children.

Parameters:

  • key (String | Symbol)

    the name of the variable to query

  • default (Proc)

    an optional block that must return the default (initial) value of this variable.

Returns:

  • (Object | nil)

    the value of the queried variable, or nil if it is not set and no default was given.



77
78
79
80
81
82
83
84
85
86
# File 'lib/mongoid/threaded.rb', line 77

def get(key, &default)
  result = storage[key]

  if result.nil? && default
    result = yield
    set(key, result)
  end

  result
end