Real-time Web Applications with Ruby on Rails

Ruby on Rails can be used now to build real-time web applications out of the box!

From version 5, the Rails framework incorporates ActionCable, an integrated websocket implementation.

ActionCable is a full-stack offering that provides both a client-side JavaScript framework and a server-side Ruby framework.

The terminology for a simple configuration is explained in the diagram below:

The diagram shows that there is one between client and server, one that is connected at the client by a , and a that it is a link to transmit messages from the server to all channel subscribers.

This configuration is generated automatically with the rails command , we need to provide the name of the channel and the name of an action.

The action name becomes a javascript method in the client, that when it is called, it triggers the ruby method of the same name in the server.

For example the command:

$ rails generate channel room speak

It creates three files:

  • A channel server file in ruby: app/channels/room_channel.rb
  • A channel client file in javascript :app/assets/javascripts/channels/
  • A client initialisation file: app/assets/javascripts/cable.js

The client initialisation file contains boiler plate code to initialise the connection.

For the moment let’s focus on the channel files.

The client side channel

The file creates the subscription to the “RoomChannel”, contains callbacks and user defined functions:

The server will invoke connected, disconnected and received(data) when these events take place.

The javascript client will invoke speak(notice) when needs to send data to the server.

The server side channel

The file represents the channel, contains call backs and user defined actions:

The subscribed method is called by rails when a new client creates a subscription to the channel; and the subscription is said to stream_from the broadcasting named ‘room_channel’.

The unsubscribed method is called when the client unsubscribes from the channel.

The is called by rails when the client invokes “@perform ‘speak’”. In this case, the server uses the broadcasting ‘room_channel’ to send to each client the data that has arrived.

The ActionCable.server.broadcast method will make that the callback is performed at the client. A pop-up alert message should appear at the client.

This concludes a brief introduction to ActionCable. We have shown how to create achannel and described the client-side and server-side files for a a simple example.

The complete source code for this example is available here.

In this webcasting from a presentation I gave at the London Ruby User Group, I explain step by step how to build this example and provide more information on the technologies that makes this possible.

If you have any questions about the topic please feel free to comment and ask!