...

/

Immediate Communication with Action Cable

Immediate Communication with Action Cable

Learn about immediate communication with Action Cable.

Let’s look at an example of using Action Cable to broadcast sold-out concert data to our schedule page. We’ll need to write some code server-side and some code client-side. On the server-side, we need to create a channel and also set up the place where data is sent to that channel. On the client-side, we need to respond to data when it’s sent.

We’ve set up this functionality to be the most basic Action Cable as possible—the data only flows one way from the server to the client, and the identical broadcast goes to all subscribers. The schedule is the same for everybody.

Generating boilerplate

We can start by asking Rails to generate some boilerplate:

% rails generate channel ScheduleChannel

This will generate two files: a server-side file app/channels/schedule_channel.rb and a client-side file app/javascripts/channels/schedule_channel.js.

If this is your first Action Cable Rails generation, Rails will also create an index.js file for app/javascripts/channels. Like the similar file created for Stimulus controllers, this will automatically load any file in that directory ending in _channel.js.

Rails will also create a file at app/javascripts/consumer.js, which frankly, is an odd little shortcut for calling the Action Cable method createConsumer. It will make more sense in a minute when I talk about our client-side code. We are going to ignore these boilerplate files and integrate Action Cable ourselves.

Server-side

First, we need to define the channel on the server-side. The channel does not do very much here:

Press + to interact
#---
# Excerpted from "Modern Front-End Development for Rails",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/nrclient for more book information.
#---
class ScheduleChannel < ApplicationCable::Channel
def subscribed
stream_from("schedule")
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end

The two methods, subscribed and unsubscribed, are automatically called by Action Cable when a new connection subscribes and when that connection ...