Action Cable ‘Hello World’ with Rails 5.1

Most people have seen examples of Action Cable chat applications. I find them too big for a quick introduction to the idea of Action Cable. For my new “Learn Rails 5.1” book I created a smaller, easier to replicate and to understand example where we send a piece of “Hello World!” HTML from the console to the already loaded webpage.

Do you prefer a screencast? You’ll find one at the bottom of this page.

What we want to achieve

Broadcasting a piece of HTML code to a channel from the Rails console.

Use Action Cable to shoot a “Hello World!” from the console to the web browser.

The Rails Application Setup

We start with a new Rails application:

Change the routes for easier navigation:

config/routes.rb

And add some HTML to the view:

app/views/page/index.html.erb

To append HTML to the `<div id=”messages”></div>` in the DOM we need to use jQuery which is not integrated by default in Rails 5.1.

In Rails 5.1 this is done with the new JavaScript packet manager Yarn which you have to install first (non macOS users have to look the installation up at https://yarnpkg.com/en/docs/install):

Than you can use it to install jQuery:

To actually load jQuery we have to add this line:

app/assets/javascripts/application.js

Creating a Channel

Rails provides a handy generator to create a new channel. We call this channel “WebNotifications”.

And we add some CoffeeScript top get things going:

app/assets/javascripts/page.coffee

Lastly we have to add this code to the channel.

app/channels/web_notifications_channel.rb

Unfortuntly we can not push messages from a Rails console to a Rails server in a different terminal in the development default setup. We have to activate the Redis gem first by including this line in the ‘Gemfile’. Obviously you have to have a running Redis on your system (e.g. brew install redis on a macOS).

Gemfile

Followed by a run of bundle again.

We have to configure the use of Redis:

config/cable.yml

Start the server

Finally it’s time to start up our development rails server:

rails server

And the console in a different terminal. In that console we can broadcast a message to the web_notifications_channel:

That’s it! Find more information about Action Cable at http://edgeguides.rubyonrails.org/action_cable_overview.html.

For updates and other screencasts follow me on Twitter https://twitter.com/wintermeyer

The Screencast

Shameless Plug
Yes, I do offer Rails Training and Consulting. Please send me an email to stefan.wintermeyer@amooma.de