Setup

How to get setup with CableReady

Installation

bundle add cable_ready
yarn add cable_ready

ActionCable Setup

bundle exec rails generate channel example
app/channels/example_channel.rb
class ExampleChannel < ApplicationCable::Channel
def subscribed
stream_from "example-stream"
end
end
app/javascript/channels/example_channel.js
import CableReady from 'cable_ready'
import consumer from './consumer'
consumer.subscriptions.create('ExampleChannel', {
received (data) {
if (data.cableReady) CableReady.perform(data.operations)
}
})

Application Setup

app/views/home/index.html.erb
<h1>What will happen?</h1>
<div id="content"></div>

You can call ActionCable from an ActiveJob, an ActiveRecord callback, a rake task, inside of a StimulusReflex action method. Here we'll launch an ActiveJob from our controller. Five seconds after the page loads, you will see an update.

app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
ExampleJob.set(wait: 5.seconds).perform_later
end
end

Note that you cannot broadcast inside of a controller action directly, as the data will be sent immediately - that is, before the page is rendered and delivered - so the message will be missed.

app/jobs/example_job.rb
class ExampleJob < ApplicationJob
include CableReady::Broadcaster
queue_as :default
def perform(*args)
cable_ready["example-stream"].inner_html(
selector: "#content",
html: "Hello World this is the background job."
)
cable_ready.broadcast
end
end

CableReady supports quite a few DOM operations that can be broadcast to connected clients. View the full list here.

Misc

By default, CableReady will emit a warning to the console log if it cannot find a DOM element matching the specified selector. If you would prefer to silently ignore operations on elements that don't exist, CableReady.perform accepts an options object as a second parameter: CableReady.perform(data.operations, { emitMissingElementWarnings: false })