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 “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.
BTW: There is a new version of this how-to in my Learn Rails 5.2 book.
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.
The Rails Application Setup
We start with a new Rails application:
Change the routes for easier navigation:
And add some HTML to the view:
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.
Than you can use it to install jQuery:
To actually load jQuery we have to add this line:
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:
Lastly we have to add this code to the channel.
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).
Followed by a run of
We have to configure the use of Redis:
Start the server
Finally it’s time to start up our development 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
Yes, I do offer Rails Training and Consulting. Please send me an email to firstname.lastname@example.org