Skip to content

Instantly share code, notes, and snippets.

@hypomodern
Created May 13, 2011 15:17
Show Gist options
  • Save hypomodern/970721 to your computer and use it in GitHub Desktop.
Save hypomodern/970721 to your computer and use it in GitHub Desktop.
How do I use EM::Synchrony::Multi inside a controller action?
# So, I have an controller action that makes multiple calls to third-party APIs over http.
# I'd like to parallelize these calls via EventMachine::Synchrony::Multi, but can't figure out how to wire the controller
#
# This works fine from, say, a script on the command line, but not in a controller running on a thin server.
#
# What I was missing: a) rack/fiber_pool, b) we don't need the EM.synchrony block
class DemoController < ApplicationController # or a sinatra app, same result
# ...
def evented
multi = nil
# EM.synchrony do # <= you don't need this synchrony block
multi = EventMachine::Synchrony::Multi.new
# queue up a bunch of hopefully-asynchronous API calls
5.times do |i|
multi.add i, EM::HttpRequest.new("http://search.twitter.com/search?q=rails+3&format=json").aget
end
multi.perform
# EM.stop # causes application to exit if present
# end # <= just call multi.perform
# parsing of results omitted...
render :text => multi.inspect # the multi object has no responses.
end
end
@mattgreen
Copy link

Did this end up working out for you? It appears it did, but I'm curious if you had any thoughts on it after the fact.

Also, do I have to use Thin?

@hypomodern
Copy link
Author

Thin or rainbows--those are the only two evented ruby webservers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment