Class: GraphQL::Execution::Lazy

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/execution/lazy.rb,
lib/graphql/execution/lazy/resolve.rb,
lib/graphql/execution/lazy/lazy_method_map.rb

Overview

This wraps a value which is available, but not yet calculated, like a promise or future.

Calling #value will trigger calculation & return the "lazy" value.

This is an itty-bitty promise-like object, with key differences:

  • It has only two states, not-resolved and resolved
  • It has no error-catching functionality

Defined Under Namespace

Modules: Resolve Classes: LazyMethodMap

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target = nil, method_name = nil, &get_value_func) ⇒ Lazy

Create a GraphQL::Execution::Lazy which will get its inner value by calling the block

Parameters:

  • target (Object) (defaults to: nil)
  • method_name (Symbol) (defaults to: nil)
  • get_value_func (Proc)

    a block to get the inner value (later)



25
26
27
28
29
30
31
32
33
# File 'lib/graphql/execution/lazy.rb', line 25

def initialize(target = nil, method_name = nil, &get_value_func)
  if block_given?
    @get_value_func = get_value_func
  else
    @target = target
    @method_name = method_name
  end
  @resolved = false
end

Class Method Details

.resolve(val) ⇒ Object

Traverse val, lazily resolving any values along the way

Parameters:

  • val (Object)

    A data structure containing mixed plain values and Lazy instances

Returns:

  • void



17
18
19
# File 'lib/graphql/execution/lazy.rb', line 17

def self.resolve(val)
  Resolve.resolve(val)
end

Instance Method Details

#then(&block) ⇒ Lazy

Returns A GraphQL::Execution::Lazy whose value depends on another GraphQL::Execution::Lazy, plus any transformations in block.

Returns:



52
53
54
55
56
# File 'lib/graphql/execution/lazy.rb', line 52

def then(&block)
  self.class.new {
    next_val = block.call(value)
  }
end

#valueObject

Returns The wrapped value, calling the lazy block if necessary.

Returns:

  • (Object)

    The wrapped value, calling the lazy block if necessary



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/graphql/execution/lazy.rb', line 36

def value
  if !@resolved
    @resolved = true
    if @get_value_func
      @value = @get_value_func.call
    else
      @value = @target.public_send(@method_name)
    end
  end
  @value
rescue GraphQL::ExecutionError => err
  @resolved = true
  @value = err
end