Skip to content

Instantly share code, notes, and snippets.

@igrigorik igrigorik/gist:60421 forked from tmm1/gist:58437
Created Feb 8, 2009

Embed
What would you like to do?
##
# 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
You can’t perform that action at this time.