Class: Farce::Abstract::Lazy Abstract

Inherits:
Object
  • Object
show all
Includes:
Value, Internal::Copyable, Internal::Inspect, Internal::MarshalSupport::Initialize
Defined in:
lib/farce/abstract/lazy.rb

Overview

This class is abstract.

Shared factory, caching, and delegation behavior for lazy values.

Direct Known Subclasses

Lazy, Local::Lazy, Strict::Lazy, Unshared::Lazy

Instance Method Summary collapse

Methods included from Value

#blank?, #unwrap

Methods included from Internal::Copyable

#duplicable?

Constructor Details

#initialize(factory) ⇒ Lazy #initialize(self: nil) { ... } ⇒ Lazy

Returns a new instance of Lazy.

Overloads:

  • #initialize(factory) ⇒ Lazy

    Parameters:

    • factory (Class, Proc, #call) —

      The factory to use for creating the value. Must be ractor-shareable.

  • #initialize(self: nil) { ... } ⇒ Lazy

    Parameters:

    • self (BasicObject) (defaults to: nil) —

      The self parameter to be provided to the block. Must be ractor-shareable.

    Yields:

    • The block to use for creating the value. Must be ractor-shareable.

    Yield Returns:

    • (BasicObject) —

      The value to be returned by the lazy instance.

    Yield Receiver:

    • (BasicObject) —

      The self parameter provided, or nil if not provided.



22
23
24
25
26
# File 'lib/farce/abstract/lazy.rb', line 22

def initialize(factory = nil, **, &)
  @factory = prepare_factory(factory, **, &)
  @atom    = new_internal_atom
  super()
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing ⇒ BasicObject (private)

Delegates all method calls to #value.



111
# File 'lib/farce/abstract/lazy.rb', line 111

def method_missing(...) = value.public_send(...)

Instance Method Details

#value ⇒ BasicObject

The first time this method is called, the value will be computed based on the factory provided. Subsequent calls will return the same value.

Concurrent access computes the value once. Shareable variants support calls from any Ractor.

Returns:

  • (BasicObject) —

    The value computed by the factory.



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/farce/abstract/lazy.rb', line 34

def value
  atom  = internal_atom
  value = atom.value
  if value.nil?
    value = atom.store_if_absent do
      value = compute_value
      value.nil? ? UNDEFINED : value
    end
  end
  value unless UNDEFINED.equal?(value)
end