How do you spawn an EventMachine "inside" a Rails app? How do you spawn an EventMachine "inside" a Rails app? ruby ruby

How do you spawn an EventMachine "inside" a Rails app?


You cannot run the Eventmachine engine inside of Rails itself as it is a persistent run loop that would block one of your Rails processes permanently. What is usually done is there's a side-process that uses Eventmachine and Rails communicates with it through sockets to send notifications.

Juggernaut serves as an example of this kind of thing where it implements a Websocket client and a Rails hook to send notifications to it. The project has since deprecated the Ruby version in favor of a JavaScript Node.js version but this still serves as a very thorough example of how Eventmachine can be used.


If you run rails application in a thin server (bundle exec thin start) thin server run EventMachine for you and then your rails application can execute EM code wherever you need.

By example:

A library o initializer with that code:

EM.next_tick do  EM.add_periodic_timer(20) do    puts 'from Event Machine in rails code'  endend

not blocks rails processes application.


Don't know if this is what you are after. But if you would like to do provide some kind of socket-messaging system.

Have a look at Faye. It provides message servers for Node.js and Rack. There is also a rails cast for this by Ryan Bates which should simplify the implementation.

Hope that helps.