Skip to content

Instantly share code, notes, and snippets.

@textgoeshere
Created July 12, 2013 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save textgoeshere/5983929 to your computer and use it in GitHub Desktop.
Save textgoeshere/5983929 to your computer and use it in GitHub Desktop.
#!/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?
!@thread.alive?
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