Created
September 17, 2012 05:51
-
-
Save wuputah/3735764 to your computer and use it in GitHub Desktop.
Later: a simple thread proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# +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