Skip to content

Instantly share code, notes, and snippets.

@godfat
Created August 30, 2012 20:56
Show Gist options
  • Save godfat/3540749 to your computer and use it in GitHub Desktop.
Save godfat/3540749 to your computer and use it in GitHub Desktop.
# Wrap a fiber around app_call
Fiber.new{
# [...]
# Below is modified from event_machine/client.rb, in def app_call input,
# but let's forget about :async for now.
# In APP.call, it would call Fiber.yield whenever we're waiting for data.
status, headers, body = APP.call(@env.merge!(RACK_DEFAULTS))
# The response is fully ready at this point.
ev_write_response(status, headers, body, @hp.next?)
}.resume
# * * * * *
# Here's the app
APP = lambda{ |env|
# First we remember where we need to jump back
f = Fiber.current
# Wait for 5 seconds to emulate waiting for data
EM.add_timer(5){
# Here then we have data available, let's resume back.
# But we also wrap resuming in a next_tick block,
# giving EM some chances to cleanup it's internal states.
EM.next_tick{
f.resume('OK')
}
}
# Here we immediately yield and give control back to Rainbows!
# and Rainbows! would then go back to EventMachine's regular loop,
# buffering requests, making requests, etc.
body = Fiber.yield
# So now body is referring the data resumed from above.
# Rainbows! should handle the response at this point.
[200, {}, [body]]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment