class PurePromise::Coercer

Public Class Methods

coerce(*args, &block) click to toggle source
# File lib/pure_promise/coercer.rb, line 12
def self.coerce(*args, &block)
  new(*args, &block).coerce
end
is_thenable?(thenable) click to toggle source
# File lib/pure_promise/coercer.rb, line 8
def self.is_thenable?(thenable)
  thenable.respond_to?(:then)
end
new(thenable, promise_class) click to toggle source
# File lib/pure_promise/coercer.rb, line 16
def initialize(thenable, promise_class)
  raise TypeError, 'Can only coerce a thenable' unless self.class.is_thenable?(thenable)
  @thenable = thenable
  @promise_class = promise_class
end

Public Instance Methods

coerce() click to toggle source
# File lib/pure_promise/coercer.rb, line 22
def coerce
  return @thenable if @thenable.instance_of?(@promise_class)

  @mutated = false
  coerce_thenable
end

Private Instance Methods

build_callback(promise, method) click to toggle source
# File lib/pure_promise/coercer.rb, line 44
def build_callback(promise, method)
  proc do |value|
    mutate_promise { promise.public_send(method, value) }
    promise
  end
end
coerce_thenable() click to toggle source
# File lib/pure_promise/coercer.rb, line 31
def coerce_thenable
  @promise_class.new.tap do |promise|
    begin
      @thenable.then(
          build_callback(promise, :fulfill),
          build_callback(promise, :reject)
      )
    rescue Exception => error
      mutate_promise { promise.reject(error) }
    end
  end
end
mutate_promise() { || ... } click to toggle source
# File lib/pure_promise/coercer.rb, line 51
def mutate_promise
  unless @mutated
    yield
    @mutated = true
  end
end