Sha256: 85019164ad7992545e15dd6e62fb19670547d47e6b858d447aa611c34b87707e

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

require 'promising/promise'

##
# A delayed-execution result, optimistically evaluated in a new thread.
#
# @example
#   x = future { sleep 5; 1 + 2 }
#   # do stuff...
#   y = x * 2     # => 6.  blocks unless 5 seconds has passed.
#
module Promising
  class Future < defined?(BasicObject) ? BasicObject : Object
    instance_methods.each { |m| undef_method m unless m =~ /^(__.*|object_id)$/ }
  
    ##
    # Creates a new future.
    #
    # @yield  [] The block to evaluate optimistically.
    # @see    Kernel#future
    def initialize(timeout:nil,&block)
      @promise = Promise.new(timeout:timeout,&block)
      @thread  = ::Thread.new{@promise.__force__}
    end
  
    ##
    # The value of the future's evaluation.  Blocks until result available.
    #
    # @return [Object]
    def __force__
      @thread.join if @thread
      @promise
    end
    alias_method :force, :__force__
  
    ##
    # Does this future support the given method?
    #
    # @param  [Symbol]
    # @return [Boolean]
    def respond_to?(method, include_all=false)
      :force.equal?(method) || :__force__.equal?(method) || __force__.respond_to?(method, include_all)
    end
  
    private
  
    def method_missing(method, *args, &block)
      __force__.__send__(method, *args, &block)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
promising-0.3.1 lib/promising/future.rb