Realtime Client Push to Rails Application with Pusher
One Wednesday in August my friend calls and tells me there’s a soccer tournament that he’d like to do reporting on and publish it live online. He intends to post scores, photos and do live play-by-play like text reporting. All he needs is the app to do that and the tournament is in two days, so the time window is short. So I need to get busy quickly.
Soon we can upload photos and post live updates of what would be happening on the pitch. We’d have a “live page” where all the action would get posted and we would like to have the newest content on the screens of our audience as soon as possible. One way would be to have the client browsers making Ajax requests, say every 30 seconds, and pull new stuff if there were any. But that’d surely result in a lot of unnecessary requests. There has to be a better way.
It turns out there’s a realtime push service named Pusher. With Pusher, the client browsers connect to the service with WebSockets and listen to a channel for events. Your Rails application talks to Pusher service and triggers events.
Pusher is in public beta, so I signed up to try it out. They have a good Quickstart Guide which covers everything you need to get up and running.
You’ll need the Pusher gem that deals with the server communication so go ahead and install it.
$ gem install pusher
Next, I created config/initializers/pusher.rb Rails initializer to hold Pusher gem configuration. I added app_id, key and secret to the initializer so that the interface would be properly configured for me in the application.
On the live page we had an scrolling image gallery and the play-by-play feed. So I bound the client to a few events that would be triggered when new content would be posted. These are defined in JavaScript.
Whenever I would create a new entry to play-by-play feed, “entry-posted” event was sent to the “live” channel and the entry was added to the top of the stack of entries and faded in. When I uploaded a new photo to the gallery, “image-posted” event was sent to the “live” channel and the photo would be added to the image gallery.
In the controllers for entries and photos, I’d trigger Pusher events like this.
That’s it! As you can see, Pusher is super simple to use and very useful. You can offload the content push to Pusher service and don’t have to tax your app server with Ajax requests. Also, updates are pushed to the clients immediately instead of some delay that one might have if one had a recurring Ajax request happening to pull possible new content.
// Lauri