Skip to content

Instantly share code, notes, and snippets.

@wuputah
Created Sep 17, 2012
Embed
What would you like to do?
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