Skip to content

Instantly share code, notes, and snippets.

@wuputah
Created September 17, 2012 05:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wuputah/3735764 to your computer and use it in GitHub Desktop.
Save wuputah/3735764 to your computer and use it in GitHub Desktop.
Later: a simple thread proxy
# +Later+ is a typical object proxy built around a Thread. You pass it a block
# and it will start performing that task in a Thread. Later, you can call any
# method on the object and it will proxy the call to the return value from
# +Thread#value+ (which joins the thread).
#
# Example:
#
# data = [
# Later { open("http://google.com") },
# Later { open("http://duckduckgo.com") },
# Later { open("http://heroku.com") }
# ]
# puts data.map(&:size)
#
require 'thread'
class Later < BasicObject
def initialize(*args, &block)
@thread = ::Thread.new(*args, &block)
end
def method_missing(*args, &block)
@thread.value.send(*args, &block)
end
def respond_to?(method)
@thread.value.respond_to?(method)
end
def ==(obj)
@thread.value == obj
end
end
# Convenience method to call +Later.new+
def Later(*args, &block)
Later.new(*args, &block)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment