Skip to content

Instantly share code, notes, and snippets.

@igrigorik
Forked from tmm1/gist:58437
Created February 8, 2009 16:42
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 igrigorik/60421 to your computer and use it in GitHub Desktop.
Save igrigorik/60421 to your computer and use it in GitHub Desktop.
##
# sync api: return values and exceptions
begin
images = []
results = RestClient.get('http://google.com/search?q=ruby')
Hpricot(results).find('a').each{ |link|
page = RestClient.get(link)
begin
images << Hpricot(page).find('img')
rescue RestClient::RequestFailed
end
}
images.flatten.each{ |img| p(img) }
rescue RestClient::RequestFailed
pus 'error!'
end
##
# async api: separate callback and errback blocks
request = EM::HttpClient.get('http://google.com/search?q=ruby')
request.errback{ puts 'error!' }
request.callback{ |results|
images = []
link = Hpricot(results).find('a')
num_links = links.size
on_images_done = proc{
images.flatten.each{ |img| p(img) }
}
links.each{ |link|
page_request = EM::HttpClient.get(link)
page_request.callback{ |page|
images << Hpricot(page).find('img')
num_links -= 1
if num_links == 0 # all pages fetched
on_images_done.call
end
}
page_request.errback{
num_links -= 1
if num_links == 0 # all pages fetched
on_images_done.call
end
}
}
}
##
# fibered compat layer: sync interface to async code
def RestClient.get url
f = Fiber.current
request = EM::HttpClient.get(url)
request.callback{|page| f.resume(page) }
request.errback{ f.resume(RestClient::RequestFailed.new) }
retval = Fiber.yield
raise retval if retval.is_a? Exception
return retval
end
Fiber.new{
results = RestClient.get('http://google.com/search?q=ruby')
}.resume
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment