Skip to content

Instantly share code, notes, and snippets.

@sleroux
Created January 18, 2013 20:58
Show Gist options
  • Save sleroux/4568466 to your computer and use it in GitHub Desktop.
Save sleroux/4568466 to your computer and use it in GitHub Desktop.
Using Fibers to write linear callback code
require 'eventmachine'
require 'em-http'
require 'fiber'
# Borrowed from http://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/
def async_fetch(url)
# Grab a reference to which fiber I am
f = Fiber.current
http = EventMachine::HttpRequest.new(url).get :timeout => 10
# The cool part - tell this fiber to resume when the HTTP callbacks happen.
# This will start back up the fiber and continue where it left off
http.callback { f.resume(http) }
http.errback { f.resume(http) }
# Pass the ball to someone else
return Fiber.yield
end
EventMachine.run {
# Fibers are the new hotness
Fiber.new {
data = async_fetch('http://ww.google.com')
# Happens after the yield
puts "Fetched page 1: #{data.response_header.status}"
EventMachine.stop
}.resume
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment