Sha256: eb160460e2aaf844946f216859ead480b1056e90dc24d98833837854c0507f8b

Contents?: true

Size: 960 Bytes

Versions: 1

Compression:

Stored size: 960 Bytes

Contents

require 'promise'

##
# A delayed-execution result, optimistcally evaluated in a new Thread.
# @example
#     x = future { sleep 5; 1 + 2 }
#     # do stuff...
#     y = x * 2     # => 6.  blocks unless 5 seconds has passed.
# 
class Future < defined?(BasicObject) ? BasicObject : Object

  instance_methods.each { |m| undef_method m unless m =~ /__|object_id/ } unless defined?(BasicObject)
  
  ##
  # @param [Proc] block
  # @return [Future]
  def initialize(block)
    @promise = promise &block
    @thread = ::Thread.new do
      @promise.force
    end
  end

  ##
  # The value of the future's evaluation.  Blocks until result available.
  # @return [Any]
  def force
    @thread.join
    @promise
  end

  # @private
  def method_missing(method, *args, &block)
    @promise.send(method, *args, &block) 
  end


end


module Kernel

  # Create a new future 
  # @example
  #     x = future { 3 + 3 }
  def future(&block)
    Future.new(block)
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
promise-0.1.1 lib/future.rb