Embedding Faye into Rails

So, realtime messaging is the main topic of this post, one of the option that i’m going to cover in this post is Faye. We can find a good tutorial by Ryan Bates on how to use Faye in Railscasts in this episode. In there, we have a rails application as the main interface to the user and a service for the messaging in a separated service using Faye. That’s doesn’t fit my needs, I want to also do some processing with the messages to the database and other services.

To deal with this situation we will need to use faye-rails created by James Horton. We will need to run the application only with Thin, because typical rails rack-based server can’t handle open connection that needed by Faye and only Thin who can do this. First, add this to Gemfile:

gem 'faye-rails'

Run bundle install then add to config/routes.rb routing to the action we want, let’s say:

faye_server '/stream', timeout: 25 do
end

The routing rules above will set /stream path as the messaging resource, so make sure you’ve also add normal rails routing to the /stream path in the config/routes.rb, let’s say in home_controller and stream action and create the corresponding controller and with action (empty action is enough for now, we can create more advanced processing in here later).

We need to load the faye.js resource (this is the same name with faye routes we created before), we can do this by link the javascript like this in application template:

javascript_link_tag 'http://localhost:3000/stream.js'

Then create the view for the /stream path in the controller we created before, let’s say app/views/home/stream.html.erb, and put this javascript function to see the result of the messaging system:

<script type="text/javascript">
  $(function(){
    var faye = new Faye.Client('http://localhost:3000/stream');
    faye.subscribe('/stream/new', function(data){
      console.log(data);
    });
  });
</script>

We’ve owned everything we need so far, the javascript function above will subscribe to ‘/stream/new’ events, each time new stream available it will log to the console the data being sent. So, let’s start our server using thin by run this command:

rails s thin

To see how is it going, let’s run a curl command that post a new stream message to the faye server:

curl http://localhost:9292/stream -d 'message={"channel":"/stream/new", "data":"hello"}'

And we should see on the browser console data ‘hello’ we’ve sent before.