Skip to content

Instantly share code, notes, and snippets.

@samstokes
Created November 14, 2011 22:08
Show Gist options
  • Save samstokes/1365359 to your computer and use it in GitHub Desktop.
Save samstokes/1365359 to your computer and use it in GitHub Desktop.
DG example: bind: following links on a Google search
EM.run do
fetch('http://google.com/search?q=deferrable_gratification').bind! do |doc|
fetch((doc / 'ol' / 'li' / 'a')[0][:href])
end.bind! do |doc|
fetch((doc / '#repository_homepage').at(:a)[:href])
end.callback do |doc|
puts doc.at(:title).inner_text
# now the previous 'doc's aren't in scope, so I can't accidentally
# refer to them
end.errback do |error|
puts "Error: #{error}"
end.bothback { EM.stop }
end
EM.run do
fetch('http://google.com/search?q=deferrable_gratification').callback do |doc1|
fetch((doc1 / 'ol' / 'li' / 'a')[0][:href]).callback do |doc2|
fetch((doc2 / '#repository_homepage').at(:a)[:href]).callback do |doc3|
puts doc3.at(:title).inner_text
# I could also have mistyped 'doc3' as 'doc2' and got the wrong
# behaviour, but no exception to flag it
end.errback do |error|
puts "Error finding homepage link: #{error}"
end.bothback { EM.stop }
end.errback do |error|
puts "Error loading first search result: #{error}"
EM.stop
end
end.errback do |error|
puts "Error retrieving search results: #{error}"
EM.stop
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment