Created
July 12, 2013 11:58
-
-
Save textgoeshere/5983929 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby | |
require 'open-uri' | |
require 'timeout' | |
class Future < BasicObject | |
def initialize(callable) | |
@thread ||= ::Thread.new { callable.call } | |
end | |
def value | |
@thread.value | |
end | |
def ready? | |
@thread.status === false | |
end | |
def dead? | |
[email protected]? | |
end | |
def method_missing(method, *args) | |
value.send(method, *args) | |
end | |
def respond_to_missing?(method, include_private = false) | |
value.respond_to?(method, include_private) | |
end | |
end | |
module Kernel | |
def future(&block) | |
Future.new(block) | |
end | |
end | |
a = future { open("http://www.google.com") } | |
b = future { open("http://www.bing.com") } | |
c = future { throw :rubbish } | |
futures = [a, b, c].cycle | |
puts "start" | |
result = begin | |
Timeout.timeout(5) { futures.detect(&:ready?) } | |
rescue Timeout::Error | |
future.detect(&:dead?) | |
end | |
p result.readlines.grep(/title/).first.match(/\<title\>(?<title>[^\>]+)\<\/title\>/)[:title] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment