Class: WebFunction::Promise

Inherits:
Object
  • Object
show all
Defined in:
lib/web_function/promise.rb

Overview

A promise is a placeholder for a value that will be resolved later.

Examples:

pipeline = WebFunction::Pipeline.new("https://pipe.example/exec")
promise = pipeline.add_step({})
promise.resolve # => { "a" => 1 }

Defined Under Namespace

Classes: Path

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pipeline, path) ⇒ Promise

Returns a new instance of Promise.



12
13
14
15
16
# File 'lib/web_function/promise.rb', line 12

def initialize(pipeline, path)
  @pipeline = pipeline
  @path = Path.new(path)
  @value = nil
end

Instance Attribute Details

#valueObject

Returns the value of the promise.

Returns:

  • (Object)

    The value of the promise

Raises:



128
129
130
131
132
133
134
# File 'lib/web_function/promise.rb', line 128

def value
  unless @value
    raise WebFunction::UnresolvedPromiseError
  end

  @value
end

Instance Method Details

#[](key) ⇒ Object

Returns the value of the promise at the given key.

Parameters:

  • key (String, Symbol, Integer)

    The key to resolve

Returns:

  • (Object)

    The value of the promise at the given key



114
115
116
117
118
119
120
# File 'lib/web_function/promise.rb', line 114

def [](key)
  if @value
    @value[key]
  else
    @path[key]
  end
end

#resolveObject

Resolves the promise.

Returns:

  • (Object)

    The value of the promise



140
141
142
143
144
145
146
147
148
# File 'lib/web_function/promise.rb', line 140

def resolve
  if @value
    return @value
  end

  @pipeline.execute

  value
end

#to_json(*args) ⇒ String

Returns the JSON representation of the promise.

Parameters:

  • args (Array)

    The arguments to pass to the JSON.generate method

Returns:

  • (String)

    The JSON representation of the promise



100
101
102
103
104
105
106
# File 'lib/web_function/promise.rb', line 100

def to_json(*args)
  if @value
    @value.to_json(*args)
  else
    @path.to_json(*args)
  end
end

#to_sString

Returns the string representation of the promise.

Returns:

  • (String)

    The string representation of the promise



86
87
88
89
90
91
92
# File 'lib/web_function/promise.rb', line 86

def to_s
  if @value
    @value.to_s
  else
    @path.to_s
  end
end