### Example Job and View Implementation Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-everywhere.md A basic setup showing a view with a target div and a controller triggering a background job. ```html What could possibly happen?
``` ```ruby class HomeController < ApplicationController def index ExampleJob.set(wait: 5.seconds).perform_later current_user.id end end ``` -------------------------------- ### Install CableReady dependencies Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/hello-world/installation.md Install the required Ruby gem and npm package for your project. ```bash bundle add cable_ready yarn add cable_ready ``` -------------------------------- ### Install CableReady JavaScript Client Source: https://github.com/stimulusreflex/cable_ready/blob/main/README.md Add the CableReady JavaScript package to your project using Yarn. ```sh yarn add cable_ready ``` -------------------------------- ### Install CableReady Rubygem Source: https://github.com/stimulusreflex/cable_ready/blob/main/README.md Add the CableReady gem to your Ruby project using Bundler. ```sh bundle add cable_ready ``` -------------------------------- ### Import AudioOperations Package Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/customization.md Install the `@cable_ready/audio_operations` package using Yarn. This package provides the `play_sound` operation. ```bash yarn add @cable_ready/audio_operations ``` -------------------------------- ### Set up ActionCable Channel to Receive Broadcasts Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Basic setup for an ActionCable channel (`ExampleChannel`) to stream from a topic and receive CableReady broadcasts. ```ruby # app/channels/example_channel.rb class ExampleChannel < ApplicationCable::Channel def subscribed stream_from "visitors" end end # app/channels/users_channel.rb class UsersChannel < ApplicationCable::Channel def subscribed stream_for current_user end end ``` -------------------------------- ### Example of Morphing a Collection with a Wrapper Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/dom-mutations.md This example demonstrates how to use the `morph` operation to update a collection of items by providing a wrapper HTML structure that includes the rendered collection. ```ruby morph( children_only: true, selector: "#bar", html: "
" + render(Bar.all) + "
" ) ``` -------------------------------- ### Install Stimulus with Webpacker Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/leveraging-stimulus.md Run this command to install Stimulus in a Rails application using Webpacker. ```bash rails webpacker:install:stimulus ``` -------------------------------- ### Client-side Channel Subscription with CableReady Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Example of subscribing to an ActionCable channel and processing received CableReady operations using `CableReady.perform`. ```javascript // 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) } }) // With async handling and error catching consumer.subscriptions.create('UsersChannel', { received(data) { if (data.cableReady) { CableReady.performAsync(data.operations) .then(payload => console.log('Operations completed', payload)) .catch(err => console.error('Operation failed', err)) } } }) ``` -------------------------------- ### Configure Custom Operations in CableReady Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Example of configuring custom operation names like `highlight_element` and `play_animation` in the CableReady initializer. ```ruby # config/initializers/cable_ready.rb CableReady.configure do |config| config.add_operation_name :highlight_element config.add_operation_name :play_animation end ``` -------------------------------- ### Using Custom Operations highlight_element and play_animation Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Example of broadcasting custom operations `highlight_element` and `play_animation` to the client. ```ruby # Using custom operations cable_ready["visitors"] .highlight_element(selector: "#important-notice", color: "red", duration: 2000) .play_animation(selector: "#logo", animation_class: "bounce", duration: 500) .broadcast ``` -------------------------------- ### Add AudioOperations to CableReady Initializer Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/customization.md Configure CableReady to recognize custom operations by adding their names to the initializer. This example adds the `play_sound` operation. ```ruby CableReady.configure do |config| config.add_operation_name :play_sound end ``` -------------------------------- ### Setup Stimulus Controller for CableReady Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/broadcasting-to-resources.md Create a Stimulus controller that acts as an ActionCable subscription consumer and a CableReady performer. It connects to the channel, receives data, and performs CableReady operations. ```javascript import { Controller } from '@hotwired/stimulus' import CableReady from 'cable_ready' export default class extends Controller { static values = { id: Number } connect() { this.channel = this.application.consumer.subscriptions.create({ channel: 'HelensChannel', id: this.idValue }, { received (data) { if (data.cableReady) { CableReady.perform(data.operations) } } }) } disconnect() { this.channel.unsubscribe() } } ``` -------------------------------- ### Accessing CableReady Channels Instance Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/methods.md Demonstrates how to get a CableReady::Channels instance using either a string identifier or a constant identifier for a resource. ```ruby cable_ready["MyIdentifier"] ``` ```ruby cable_ready[UserChannel] ``` -------------------------------- ### Use cable_ready_stream_from Helper Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Use the `cable_ready_stream_from` helper in your views to broadcast operations to specific DOM elements without manual Channel setup. ```erb <%= cable_ready_stream_from :notifications %>
``` -------------------------------- ### Implement Stimulus value callback Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/element-mutations.md Example of a Stimulus controller responding to a dataset value change. ```javascript export default class extends Controller { static values = { index: Number } indexValueChanged() { this.showSlide(this.indexValue) } // ... } ``` -------------------------------- ### Configure ActionCable Channel Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/broadcasting-to-resources.md Set up an ActionCable channel to stream updates for a specific resource. This example configures the `HelensChannel` to stream for a `Helen` record identified by its ID. ```ruby class HelensChannel < ApplicationCable::Channel def subscribed stream_or_reject_for Helen.find(params[:id]) end end ``` -------------------------------- ### Install ActionCable Polyfills for IE11 Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/hello-world/installation.md Add the '@cable_ready/polyfills' package using yarn to support older browsers like IE11. Include these polyfills before your Stimulus controllers and CableReady channels in your application's entry point. ```javascript // other stuff import '@cable_ready/polyfills' import 'channels' import 'controllers' ``` -------------------------------- ### Use XPath Selector in CableReady Operation Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/working-with-cableready.md This Ruby example demonstrates how to use an XPath selector with CableReady. Ensure `xpath: true` is passed along with the selector and the desired text content. ```ruby text_content( selector: "/html/body/div[3]/div[1]/article[1]/section[5]/ul[1]/li[10]/div[1]/div[2]", xpath: true, text: "XPath is under-utilized, but beware of side-effects changing your DOM." ) ``` -------------------------------- ### Operation Execution Order in CableReady Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/working-with-cableready.md CableReady operations are executed in the order they are defined. This example shows how chained and sequential operations result in a specific output order. ```ruby cable_ready.console_log(message: "3").console_log(message: "1") cable_ready.console_log(message: "2") ``` -------------------------------- ### Define a Resource-based Channel Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/working-with-cableready.md Example of a channel class configured to stream for a specific resource instance. ```ruby class SailorChannel < ApplicationCable::Channel def subscribed stream_for Sailor.find(params[:id]) end end ``` -------------------------------- ### Broadcasting Updates to Current User with CableReady Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/broadcasting-to-resources.md This example shows how to use CableReady to broadcast updates. The `broadcast_to(current_user)` method sends data specifically to the currently authenticated user's channel subscription. ```javascript cable_ready[UsersChannel] .text_content() .broadcast_to(current_user) ``` -------------------------------- ### Define dataset property name Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/element-mutations.md Example of the camelCased name format required for dataset properties. ```javascript name: "showSlideIndexValue" ``` -------------------------------- ### Broadcast Model Updates with CableReady Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/broadcasting-to-resources.md Implement model callbacks to automatically broadcast updates using CableReady. This example uses `after_update` to `morph` the HTML of a `Helen` instance for all subscribed clients. ```ruby class Helen < ApplicationRecord after_update do cable_ready[HelensChannel].morph( selector: dom_id(self), html: render(self) ).broadcast_to(self) end end ``` -------------------------------- ### Server-side Morph Operation Example Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/leveraging-stimulus.md Illustrates a server-side approach using a `morph` operation to update HTML content, recommended for scenarios like sorting tables instead of complex client-side DOM manipulation. ```ruby cable_ready["updates"].morph( "#table-id", render_partial("table", locals: { data: sorted_data }) ) ``` -------------------------------- ### Define a String-based Channel Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/working-with-cableready.md Example of a channel class configured to stream from a specific string identifier. ```ruby class SailorChannel < ApplicationCable::Channel def subscribed stream_from "sailor" end end ``` -------------------------------- ### Set Boolean Attribute Example Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/element-mutations.md Demonstrates setting a boolean attribute like `disabled`. The presence of the attribute makes it true, regardless of its value. An empty string is a recommended value. ```text To set the value of a Boolean attribute, such as `disabled`, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, _regardless of its actual value_, its value is considered to be `true`. The absence of the attribute means its value is `false`. By setting the value of the `disabled` attribute to the empty string (`""`), we are setting `disabled` to `true`, which results in the button being disabled. ``` -------------------------------- ### Setting Stimulus Values via Cable Ready Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/leveraging-stimulus.md Demonstrates how to use Cable Ready's `set_dataset_property` operation to update a Stimulus controller's value. This is useful for synchronizing server-side data changes with client-side controller state, as shown in the stimulus-hotkeys example. ```ruby cable_ready["stimulus_values"].set_dataset_property( "#some-element", "hotkeys", "bindings", "{\"p\": \"#foo->example#ping\"}" ) ``` -------------------------------- ### Render Resource Partial with Stimulus Attributes Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/broadcasting-to-resources.md Define the HTML structure for a resource partial, including Stimulus controller attributes and data values. This example renders a `div` for a `Helen` instance, setting its ID. ```html
I am Helen #<%= helen.id %>.
``` -------------------------------- ### Trigger CableReady from a Rails Controller Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Example of triggering a background job from a controller action to handle notifications. ```ruby class MessagesController < ApplicationController def create @message = Message.create!(message_params) NotificationJob.set(wait: 2.seconds).perform_later( @message.recipient_id, "New message from #{current_user.name}" ) head :created end end ``` -------------------------------- ### Controller using Cable Car with Operations Renderer Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Example of a Rails controller using CableReady's Cable Car to render CableReady JSON for Ajax requests, including morph and console_log operations. ```ruby class UsersController < ApplicationController include CableReady::Broadcaster def update @user = User.find(params[:id]) if @user.update(user_params) render cable_ready: cable_car .morph(selector: "#user_#{@user.id}", html: render_to_string(@user)) .console_log(message: "User updated successfully") else render cable_ready: cable_car .inner_html(selector: "#errors", html: render_to_string("shared/errors", locals: { model: @user })) .add_css_class(selector: "#user-form", name: "has-errors") end end end ``` -------------------------------- ### Initialize CableReady client Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/hello-world/installation.md Configure the CableReady client in your application entry point. ```javascript import consumer from '../channels/consumer' import CableReady from 'cable_ready' CableReady.initialize({ consumer }) ``` -------------------------------- ### Generate CableReady initializer Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/hello-world/installation.md Create a configuration file for custom operations and settings. ```bash rails generate cable_ready:initializer ``` -------------------------------- ### Configure ExampleChannel Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/hello-world/setup.md Define the `subscribed` method in your `ExampleChannel` to stream from 'visitors'. This ensures all clients subscribed to this channel receive broadcasts sent to this stream. ```ruby class ExampleChannel < ApplicationCable::Channel def subscribed stream_from "visitors" end end ``` -------------------------------- ### Configure ApplicationJob for CableReady Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-everywhere.md Include the CableReady::Broadcaster and delegate render to the ApplicationController in your base job class. ```ruby class ApplicationJob < ActiveJob::Base include CableReady::Broadcaster delegate :render, to: :ApplicationController end ``` -------------------------------- ### Configure ApplicationRecord for CableReady Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-everywhere.md Include the broadcaster and add a helper method for Secure Global IDs in your base model. ```ruby class ApplicationRecord < ActiveRecord::Base self.abstract_class = true include CableReady::Broadcaster delegate :render, to: :ApplicationController def sgid to_sgid(expires_in: nil).to_s end end ``` -------------------------------- ### Client-side Fetch with CableReady Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Demonstrates how to perform a PATCH request from the client-side and process the JSON response using CableReady.perform. ```javascript import CableReady from 'cable_ready' fetch('/users/1', { method: 'PATCH', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content }, body: JSON.stringify({ user: { name: 'New Name' } }) }) .then(response => response.json()) .then(CableReady.perform) ``` -------------------------------- ### Rails Route for Cable Car Ride Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cable-car.md Defines a GET route for `/ride` that maps to the `ride` action in the `home` controller. ```ruby Rails.application.routes.draw do get "ride", to: "home#ride" end ``` -------------------------------- ### Enabling CableReady Updates Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/updatable.md Explains how to configure `enable_cable_ready_updates` within models and associations. ```APIDOC ## `enable_cable_ready_updates` Configuration ### Description This class method registers `after_commit` callbacks to trigger Action Cable pings after database writes. It can be configured with `on:` and `if:` options. ### Parameters #### `on:` (optional) Limits updates to specific actions: `:create`, `:update`, `:destroy`, or a combination. **Examples:** ```rb # Trigger updates only on creation enable_cable_ready_updates on: :create # Trigger updates on update and destroy enable_cable_ready_updates on: [:update, :destroy] ``` #### `if:` (optional) A lambda to conditionally deliver updates. **Example:** ```rb enable_cable_ready_updates if: -> { ready? } ``` ``` -------------------------------- ### Import and Add AudioOperations to CableReady Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/customization.md Import the `AudioOperations` from the npm package and register them with CableReady in your application's pack file. This allows you to use operations like `play_sound`. ```javascript import CableReady from 'cable_ready' import AudioOperations from '@cable_ready/audio_operations' CableReady.addOperations(AudioOperations) ``` -------------------------------- ### Generate stream helper Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/hello-world/installation.md Run the generator to enable the cable_ready_stream_from helper for broadcasting operations. ```bash rails generate cable_ready:stream_from ``` -------------------------------- ### Handle Ajax Requests with CableReady Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-everywhere.md Demonstrates routing an Ajax request and performing a CableReady broadcast within a controller action. ```html <%= link_to "Console message", "users/#{current_user.id}/message", method: :patch %> ``` ```ruby patch 'users/:id/message', to: 'users#message', constraints: lambda { |request| request.xhr? } ``` ```ruby class UsersController < ApplicationController def message cable_ready[UsersChannel].console_log(message: "Hi!").broadcast_to(current_user) head :ok end end ``` -------------------------------- ### Initialize CableReady with Debug Mode Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/updatable.md Enable diagnostic console outputs by setting the debug flag to true during initialization. ```javascript import CableReady from 'cable_ready' import consumer from '../channels/consumer' CableReady.initialize({ consumer, debug: true }) ``` -------------------------------- ### Verify ActionCable Connection with Test Channel Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/troubleshooting/index.md Use these Ruby and JavaScript files to create a test ActionCable channel. This helps verify that ActionCable is correctly set up and communicating. Ensure 'import "channels"' is present in your application.js. ```ruby class TestChannel < ApplicationCable::Channel def subscribed stream_from "test" end def receive(data) puts data["message"] ActionCable.server.broadcast("test", "ActionCable is connected") end end ``` ```javascript import consumer from './consumer' consumer.subscriptions.create('TestChannel', { connected () { this.send({ message: 'Client is live' }) }, received (data) { console.log(data) } }) ``` -------------------------------- ### CableReady Operations Overview Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/index.md This documentation lists the available operations categorized by their functionality, including DOM mutations, element property changes, browser manipulations, and notifications. ```APIDOC ## CableReady Operations ### DOM Mutations - append, graft, inner_html, insert_adjacent_html, insert_adjacent_text, morph, outer_html, prepend, remove, replace, text_content ### Element Property Mutations - add_css_class, remove_attribute, remove_css_class, set_attribute, set_dataset_property, set_property, set_style, set_styles, set_value ### DOM Events - dispatch_event, set_meta ### Browser Manipulations - clear_storage, go, push_state, redirect_to, remove_storage_item, replace_state, scroll_into_view, set_cookie, set_focus, set_storage_item, set_title ### Notifications - console_log, console_table, notification, play_sound ``` -------------------------------- ### Rails 6.1 Remote Form Examples Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/troubleshooting/index.md Demonstrates how to explicitly enable remote form submissions in Rails 6.1, as `remote: true` is no longer the default. Use UJS/mrujs for seamless submissions without page reloads. ```html <%= form_with model: @foo, local: false %> <%= form_with model: @foo, data: { remote: "true" } %> <%= form_for @foo, remote: true %>
``` -------------------------------- ### Configure sanity checks Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/hello-world/installation.md Override default version mismatch behavior in the CableReady initializer. ```ruby CableReady.configure do |config| config.on_failed_sanity_checks = :warn end ``` -------------------------------- ### Mutating Morph Content Before Morphing Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/dom-mutations.md You can modify the content of a morph operation before it's applied by listening to the `cable-ready:before-morph` event. Access the `event.detail.content` to mutate the document fragment, but do not reassign it. For example, change the style of an element within the content. ```javascript document.addEventListener('cable-ready:before-morph', event => { event.detail.content.querySelector('#foo').setStyle('color', 'red') }) ``` -------------------------------- ### Configure Import Maps Source: https://github.com/stimulusreflex/cable_ready/blob/main/README.md Pin the CableReady module in your Rails importmap configuration file. ```ruby # config/importmap.rb # ... pin 'cable_ready', to: 'cable_ready.js', preload: true ``` -------------------------------- ### Skipping Cable Ready Updates for Specific Models Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/updatable.md Illustrates how to selectively skip Cable Ready broadcasts for a particular model, such as `Comment`, while allowing updates for other models like `Post` within the same block. ```ruby # Skips broadcasts for Comment only: Comment.skip_cable_ready_updates do # will not broadcast Comment.update_all(status: :published) # will broadcast Post.update_all(author: nil) end ``` -------------------------------- ### Configure Redis for Development in config/cable.yml Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/hello-world/installation.md Set up the Redis adapter for ActionCable in your development environment. This configuration uses a default URL for Redis and allows for a custom channel prefix. ```yaml development: adapter: redis url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> channel_prefix: your_application_development ``` -------------------------------- ### Complex Broadcast Scenario with Multiple Queues and Options Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/stream-identifiers.md Illustrates a complex broadcast scenario involving multiple queues ('visitors', 'chewies', 'sailors') with different broadcast options (`clear: false` and default `clear: true`). This demonstrates fine-grained control over which queues are broadcast and whether they are cleared. ```ruby cable_ready["sailors"].text_content cable_ready["visitors"].set_focus cable_ready["chewies"].remove_css_class cable_ready.broadcast("visitors", "chewies", clear: false) # visitors, chewies cable_ready.broadcast("chewies", clear: false) # chewies cable_ready.broadcast("visitors") # visitors cable_ready.broadcast # sailors, chewies ``` -------------------------------- ### CableReady::Updatable Module Integration Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/updatable.md Demonstrates how to include CableReady::Updatable in a model and enable updates. ```APIDOC ## `CableReady::Updatable` Module ### Description Include this module in your model to enable automatic real-time view updates when the model's data changes. ### Method `include CableReady::Updatable` ### Usage ```rb class Comment < ApplicationRecord include CableReady::Updatable belongs_to :feed enable_cable_ready_updates end ``` ``` -------------------------------- ### Render CableReady Operations in Controller Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cable-car.md Use the `render cable_ready:` helper in a controller action to directly render CableReady operations generated by `cable_car`. ```ruby class HomeController < ApplicationController include CableReady::Broadcaster def index render cable_ready: cable_car.console_log(message: "hi") end end ``` -------------------------------- ### Generate a CableReady Channel Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/working-with-cableready.md Run this command in your terminal to initiate the interactive generator for a new channel. ```bash rails generate cable_ready:channel Sailor ``` -------------------------------- ### Configure Stimulus Controller for Subscription Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/working-with-cableready.md HTML markup to attach a Stimulus controller and pass the resource ID for automatic subscription. ```html
``` -------------------------------- ### Append and Prepend HTML Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Insert HTML content at the beginning or end of target elements. Use select_all to apply changes to multiple matching elements. ```ruby # Append to the end of an element cable_ready["chat"] .append( selector: "#messages", html: "
#{message.body}
" ) .broadcast # Prepend to the beginning cable_ready["notifications"] .prepend( selector: "#notification-list", html: render(partial: "notifications/item", locals: { notification: @notification }) ) .broadcast # Append to multiple elements using select_all cable_ready["visitors"] .append( selector: ".feed", select_all: true, html: "
New post available
" ) .broadcast ``` -------------------------------- ### Association Extensions for CableReady Updates Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/updatable.md Details how to use `enable_cable_ready_updates` with Active Record associations like `has_many`, `has_one`, and `has_many_attached`. ```APIDOC ## Association Extensions ### `has_many` Association #### `enable_cable_ready_updates: true` Creates a stream identifier for subscribing to updates on a collection. **Example:** ```erb <%= cable_ready_updates_for @feed, :comments do %> <%= render @feed.comments %> <% end %> ``` #### `descendants` Specifies descendant classes for Single Table Inheritance. **Example:** ```rb class Section < ApplicationRecord include CableReady::Updatable has_many :blocks, enable_cable_ready_updates: true, descendants: ["Comment"] end ``` ### `has_one` Association #### `enable_cable_ready_updates: true` Creates a stream identifier for subscribing to updates on the dependent record. **Example:** ```erb <%= cable_ready_updates_for @supplier, :account do %> <%= render @supplier.account %> <% end %> ``` ### `has_many_attached` Association #### `enable_cable_ready_updates: true` Creates a stream identifier for subscribing to updates on all Active Storage attachments. **Example:** ```rb class Post < ApplicationRecord include CableReady::Updatable has_many_attached :images, enable_cable_ready_updates: true end ``` **View Helper Usage:** ```erb <%= cable_ready_updates_for @post, :images do %> <% end %> ``` ``` -------------------------------- ### Include CableReady in ApplicationCable Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-everywhere.md Include the CableReady broadcaster and delegate rendering to the ApplicationController within your base channel. ```ruby module ApplicationCable class Channel < ActionCable::Channel::Base include CableReady::Broadcaster delegate :render, to: :ApplicationController end end ``` -------------------------------- ### Subscribe to Updates in Views Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/updatable.md Use the cable_ready_updates_for helper to wrap content that should be automatically updated when the underlying model changes. ```erb
  • <%= comment.title %> - created <%= time_ago_in_words(comment.created_at) %> ago <% if comment.owner == current_user %> <% end %>
  • ``` -------------------------------- ### Using CableReady in Background Jobs Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Integrates CableReady into `ApplicationJob` and demonstrates broadcasting notifications from a `NotificationJob` to a specific user. ```ruby # app/jobs/application_job.rb class ApplicationJob < ActiveJob::Base include CableReady::Broadcaster delegate :render, to: :ApplicationController end # app/jobs/notification_job.rb class NotificationJob < ApplicationJob queue_as :default def perform(user_id, message) user = User.find(user_id) cable_ready[UsersChannel] .prepend( selector: "#notifications", html: render(partial: "notifications/item", locals: { message: message }) ) .notification(title: "New Notification", options: { body: message }) .broadcast_to(user) end end ``` -------------------------------- ### go Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/browser-manipulations.md Navigates the browser's session history by a specified delta. ```APIDOC ## go ### Description Load a specific page from the session history. You can use it to move forwards and backwards through the history depending on the value of a parameter. `delta` is the position in the history to which you want to move, relative to the current page. A negative value moves backwards, a positive value moves forwards. `delta: -1` is equivalent to pressing the browsers "Back" button. If no value is passed or if `delta` equals `0`, it has the same result as calling `location.reload()`. ### Method Not specified (assumed to be a client-side JavaScript function call) ### Parameters #### Query Parameters - **batch** (String) - Optional - add the operation to a named batch - **cancel** (Boolean) - Optional - cancel the operation (for use on client) - **delay** (Integer) - Optional - wait for n milliseconds before running - **delta** (Integer) - Optional - optional positive or negative integer ### Request Example ```javascript go({ delta: -2 }); ``` ### Response This operation does not return a response body. It manipulates browser history directly. #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### GlobalID PORO with CableReady::Updatable Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/updatable.md Demonstrates how to integrate Plain Old Ruby Objects (POROs) that conform to the Global ID protocol with CableReady's Updatable module. This requires manually triggering callbacks if ActiveRecord::Callbacks is not included. ```ruby class GlobalIdableEntity include GlobalID::Identification include CableReady::Updatable def id "fake-id" end def self.find(id) # somehow find and return an instance of this class end def fake_update CableReady::Updatable::ModelUpdatableCallbacks.new(:update).after_commit(self) end end ``` -------------------------------- ### Controller Action Rendering CableReady via Ajax Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cable-car.md The `ride` action in the `HomeController` generates an `inner_html` operation using `cable_car` and renders it using the `render cable_ready:` helper. ```ruby class HomeController < ApplicationController include CableReady::Broadcaster def ride render cable_ready: cable_car.inner_html("#users", html: "winning") end end ``` -------------------------------- ### Redirect To Operation Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Navigate the browser to a new URL, with support for Turbo/Turbolinks. ```ruby # Simple redirect cable_ready["visitors"] .redirect_to(url: "/dashboard") .broadcast # Redirect with replace (no history entry) cable_ready["visitors"] .redirect_to(url: "/login", action: "replace") .broadcast ``` -------------------------------- ### Implement custom operations with lifecycle hooks Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/customization.md Use the Utils class to support before/after events, cancellation, and delays in custom operations. ```javascript import CableReady, { Utils } from 'cable_ready' const { before, operate, after, processElements } = Utils CableReady.operations.jazzHands = (operation, callee) => { processElements(operation, element => { before(element, operation) operate(operation, () => { const { name, danceMove } = operation console.log(`Jazz hands! ${name} did the ${danceMove}.`) }) after(element, operation) }) } ``` -------------------------------- ### Set Local Storage Item with CableReady Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Use `set_storage_item` to store data in the browser's local storage. Ensure the value is JSON-serializable. ```ruby cable_ready["visitors"] .set_storage_item(key: "user_preferences", value: preferences.to_json) .broadcast ``` -------------------------------- ### Set Session Storage Item with CableReady Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Use `set_storage_item` with `type: "session"` to store data temporarily in the browser's session storage. ```ruby cable_ready["visitors"] .set_storage_item( key: "temp_data", value: "temporary", type: "session" ) .broadcast ``` -------------------------------- ### redirect_to Operation Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/browser-manipulations.md Initiates navigation to a new URL using Turbo.visit, Turbolinks.visit, or window.location.href, with options for action, batch, cancel, and delay. ```APIDOC ## POST /stimulusreflex/cable_ready/redirect_to ### Description Initiate navigation to a new URL. Techniques will be used in the following order: Turbo.visit, Turbolinks.visit, window.location.href. ### Method POST ### Endpoint /stimulusreflex/cable_ready/redirect_to ### Parameters #### Request Body - **action** (String) - Optional - "advance" (default) or "replace" - **batch** (String) - Optional - Add the operation to a named batch - **cancel** (Boolean) - Optional - Cancel the operation (for use on client) - **delay** (Integer) - Optional - Wait for n milliseconds before running - **url** (String) - Required - URL String ### Request Example ```json { "operation": "redirect_to", "data": { "url": "/new-page", "action": "advance", "delay": 100 } } ``` ### Response #### Success Response (200) - **status** (String) - Indicates success #### Response Example ```json { "status": "ok" } ``` #### Life-cycle Callback Events - `cable-ready:before-redirect-to` - `cable-ready:after-redirect-to` ``` -------------------------------- ### State Machine Transition Broadcasting Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-everywhere.md Trigger CableReady broadcasts automatically during state machine transitions. ```ruby state_machine initial: :pending do event :accept do transition [:pending] => :active end after_transition on: :accept do |post| cable_ready[PostsChannel].morph( selector: dom_id(post), html: render(post) ).broadcast_to(post) end end ``` -------------------------------- ### Include CableReady Broadcaster Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-101.md Add the CableReady::Broadcaster module to any class to enable broadcasting capabilities. ```ruby include CableReady::Broadcaster ``` -------------------------------- ### Manage temporary subscriptions in ActionCable Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/broadcasting-to-resources.md Handles subscription logic by either streaming for an existing model or creating a temporary subscription via UUID for new records. ```ruby class HelensChannel < ApplicationCable::Channel def subscribed if params[:id] stream_for(Helen.find(params[:id])) else stream_from(params[:uuid]) helen = Helen.create # sure, why not ActionCable.server.broadcast(params[:uuid], helen.id) end end end ``` -------------------------------- ### Configure scroll_into_view operation Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/browser-manipulations.md Defines parameters for scrolling an element into the viewport. Use the selector to target the element and behavior to control the animation. ```ruby scroll_into_view( batch: String, # [null] - add the operation to a named batch behavior: String, # ["auto"] - auto or smooth block: String, # ["start"] - start, center, end, nearest cancel: Boolean, # [false] - cancel the operation (for use on client) delay: Integer, # [0] - wait for n milliseconds before running inline: String, # ["nearest"] - start, center, end, nearest selector: String, # required - string containing a CSS selector or XPath expression xpath: Boolean # [false] - process the selector as an XPath expression ) ``` -------------------------------- ### Render tables in the browser console Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/notifications.md Outputs data as a table in the console, supporting column filtering via an allowlist. ```ruby console_table( batch: String, # [null] - add the operation to a named batch cancel: Boolean, # [false] - cancel the operation (for use on client) columns: Array, # [[]] - optional array of strings delay: Integer, # [0] - wait for n milliseconds before running data: Object or Array, # [{}] - required, although it can be empty ) ``` -------------------------------- ### Configure JavaScript Channel Subscriber Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/hello-world/setup.md Import CableReady and modify the `received` method in the JavaScript channel subscriber. This method checks incoming data for CableReady broadcasts and performs them. ```javascript import CableReady from 'cable_ready' import consumer from './consumer' consumer.subscriptions.create('ExampleChannel', { received (data) { if (data.cableReady) CableReady.perform(data.operations) } }) ``` -------------------------------- ### Enable CableReady Updates in Models Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/updatable.md Include the module in your Active Record models and enable updates via class method or association configuration. ```ruby class Comment < ApplicationRecord include CableReady::Updatable belongs_to :feed enable_cable_ready_updates end class Feed < ApplicationRecord include CableReady::Updatable has_many :comments, enable_cable_ready_updates: true end ``` -------------------------------- ### Include CableReady in ApplicationController Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-everywhere.md Add the CableReady broadcaster to your base controller to enable broadcasting capabilities throughout the application. ```ruby class ApplicationController < ActionController::Base include CableReady::Broadcaster end ``` -------------------------------- ### Perform CableReady Broadcast in Job Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-everywhere.md Use the cable_ready object within a job to broadcast updates to a specific channel. ```ruby class ExampleJob < ApplicationJob include CableReady::Broadcaster queue_as :default def perform(user_id) user = User.find(user_id) cable_ready[UsersChannel].inner_html( selector: "#content", html: "Hello World this is the background job." ).broadcast_to(user) end end ``` -------------------------------- ### Redirect to a new URL Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/browser-manipulations.md Initiates navigation to a new URL using Turbo, Turbolinks, or window.location.href depending on availability and domain. ```ruby redirect_to( action: String, # "advance" - other possible value is "replace" batch: String, # [null] - add the operation to a named batch cancel: Boolean, # [false] - cancel the operation (for use on client) delay: Integer, # [0] - wait for n milliseconds before running url: String # required - URL String ) ``` -------------------------------- ### Use Selector as First Parameter Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-101.md The `selector` option can be passed as the first parameter without a key for brevity when targeting DOM elements. ```ruby cable_ready["visitors"] .set_style("#foo", name: "color", value: "blue") ``` -------------------------------- ### play_sound Operation Parameters Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/notifications.md Defines the parameters for the `play_sound` operation. The `src` parameter is required. Note that this operation has been removed from the core library as of CableReady v5.0.0. ```ruby play_sound( batch: String, # [null] - add the operation to a named batch cancel: Boolean, # [false] - cancel the operation (for use on client) delay: Integer, # [0] - wait for n milliseconds before running src: String # required - URL for audio file ) ``` -------------------------------- ### Broadcast Operations with cable_ready Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Queue operations and broadcast them immediately to subscribed ActionCable clients using string identifiers. ```ruby cable_ready[:notifications] .inner_html(selector: "#messages", html: "

    Hello World!

    ") .broadcast ``` ```ruby # Queue operations and broadcast to all subscribers cable_ready["visitors"] .console_log(message: "Welcome!") .inner_html(selector: "#content", html: "

    Hello

    ") .broadcast # Broadcast to specific identifiers only cable_ready["channel_one"].append(selector: "#list", html: "
  • Item 1
  • ") cable_ready["channel_two"].append(selector: "#list", html: "
  • Item 2
  • ") cable_ready.broadcast("channel_one") # Only sends to channel_one cable_ready.broadcast # Sends remaining operations to channel_two # Keep operations in queue after broadcast cable_ready["visitors"].console_log(message: "Reusable").broadcast(clear: false) ``` -------------------------------- ### Redirect To Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Operations to navigate the browser to a new URL. ```APIDOC ## POST /stimulusreflex/cable_ready ### Description Navigates the browser to a new URL, supporting Turbo/Turbolinks. ### Method POST ### Endpoint /stimulusreflex/cable_ready ### Parameters #### Request Body - **operation** (string) - Required - The operation to perform, e.g., "redirect_to". - **url** (string) - Required - The URL to navigate to. - **action** (string) - Optional - The action to perform, e.g., "replace" to replace the current history entry. ### Request Example ```json { "operation": "redirect_to", "url": "/dashboard" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### Executing operations with performAsync Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/customization.md Uses performAsync to handle CableReady operations as a Promise, allowing for .then() and .catch() chaining. ```javascript import CableReady from 'cable_ready' import consumer from './consumer' consumer.subscriptions.create('ExampleChannel', { received (data) { if (data.cableReady) { CableReady.performAsync(data.operations).then(payload => { console.log(payload) }).catch(err => { console.log(err) }) } } }) ``` -------------------------------- ### Optimize DOM Wrapping for Updates Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/updatable.md Avoid wrapping large DOM trees in cable_ready_updates_for to prevent morph and focus restoration issues. Prefer granular updates by targeting specific attributes. ```erb <%= cable_ready_updates_for @post do %> <%= @post.updated_at %> <%= simple_format @post.body %> <% end %> <%= cable_ready_updates_for @post, only: :updated_at do %> <%= @post.updated_at %> <% end %> <%= cable_ready_updates_for @post, only: :body do %> <%= simple_format @post.body %> <% end %> ``` -------------------------------- ### Application Cable Connection with Current User Identification Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/broadcasting-to-resources.md This configuration sets up the Action Cable connection to be identified by the current user, typically by fetching the user from the warden environment. ```ruby module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user def connect reject_unauthorized_connection unless self.current_user = env["warden"].user end end end ``` -------------------------------- ### Include CableReady in Asset Pipeline Source: https://github.com/stimulusreflex/cable_ready/blob/main/README.md Add the UMD build of CableReady to your application layout using the Rails asset pipeline. ```html+erb <%= javascript_include_tag "cable_ready.umd.js", "data-turbo-track": "reload" %> ``` -------------------------------- ### Stimulus Controller for Fetching CableReady Operations Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cable-car.md A Stimulus controller that uses `fetch` to request operations from the server and then passes the JSON response to `CableReady.perform`. ```javascript import { Controller } from '@hotwired/stimulus' import CableReady from 'cable_ready' export default class extends Controller { go () { fetch('/ride') .then(r => r.json()) .then(CableReady.perform) } } ``` -------------------------------- ### Prepend Operation in CableReady Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/dom-mutations.md Use `prepend` to insert HTML into the DOM, inside the target element, before its first child. Options include batching, cancellation, delay, focus management, and selector processing. ```ruby prepend( batch: String, # [null] - add the operation to a named batch cancel: Boolean, # [false] - cancel the operation (for use on client) delay: Integer, # [0] - wait for n milliseconds before running focus_selector: String, # [null] - string containing a CSS selector html: String, # [null] - the HTML to assign select_all: Boolean, # [false] - operate on list of elements returned from selector selector: String, # required - string containing a CSS selector or XPath expression xpath: Boolean # [false] - process the selector as an XPath expression ) ``` -------------------------------- ### Subscribe to a channel with custom parameters Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/stream-identifiers.md Pass additional key-value pairs in the subscription object to send client-side data to the server. ```javascript consumer.subscriptions.create( { channel: 'SailorChannel', nickname: document.querySelector('meta[name=nickname]').content }, { connected () {}, rejected () {}, received (data) { if (data.cableReady) CableReady.perform(data.operations) } } ) ``` -------------------------------- ### Clear Session Storage with CableReady Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Use `clear_storage` with `type: "session"` to remove all items from the browser's session storage. ```ruby cable_ready["visitors"] .clear_storage(type: "session") .broadcast ``` -------------------------------- ### Add Redis and Hiredis Gems to Gemfile Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/hello-world/installation.md Include these gems in your Gemfile to enable Redis support for ActionCable. Ensure you are using Redis version 4.0 or higher. ```ruby gem "redis", ">= 4.0", :require => ["redis", "redis/connection/hiredis"] gem "hiredis" ``` -------------------------------- ### Configure set_storage_item operation Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/browser-manipulations.md Creates or updates a key/value pair in browser storage. Defaults to local storage, but supports session storage via the type parameter. ```ruby set_storage_item( batch: String, # [null] - add the operation to a named batch cancel: Boolean, # [false] - cancel the operation (for use on client) delay: Integer # [0] - wait for n milliseconds before running key: String, # required value: String, # required type: String # ["local"] - "local" or "session" ) ``` -------------------------------- ### Add Operations to Different Queues Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/stream-identifiers.md Demonstrates adding operations to separate queues for 'sailors' and 'visitors'. Each identifier has its own distinct queue. ```ruby cable_ready["sailors"].inner_html cable_ready["visitors"].set_style ``` -------------------------------- ### Set document title with CableReady Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/reference/operations/browser-manipulations.md Defines the parameters for the set_title operation, including optional batching and delay settings. ```ruby set_title( batch: String, # [null] - add the operation to a named batch cancel: Boolean, # [false] - cancel the operation (for use on client) delay: Integer, # [0] - wait for n milliseconds before running title: String, # required ) ``` -------------------------------- ### Listen for CableReady life-cycle events Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/working-with-cableready.md Register a named callback function to handle life-cycle events emitted by CableReady operations. ```javascript const afterMorphHandler = event => console.log(event.detail) document.addEventListener('cable-ready:after-morph', afterMorphHandler) ``` -------------------------------- ### Define Simple Custom Operation: highlightElement Source: https://context7.com/stimulusreflex/cable_ready/llms.txt Implements a custom CableReady operation `highlightElement` that changes an element's background color for a specified duration. ```javascript import CableReady, { Utils } from 'cable_ready' const { before, operate, after, processElements } = Utils // Simple custom operation CableReady.operations.highlightElement = operation => { processElements(operation, element => { element.style.backgroundColor = operation.color || 'yellow' setTimeout(() => { element.style.backgroundColor = '' }, operation.duration || 1000) }) } ``` -------------------------------- ### Generate an ActionCable Channel Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/cableready-101.md Use the Rails generator to create the necessary files for a new ActionCable channel. ```bash rails generate channel example ``` -------------------------------- ### Channel subscription object structure Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/stream-identifiers.md The subscription creation method accepts an object where the channel key defines the target channel. ```javascript {channel: "ExampleChannel"} ``` -------------------------------- ### Passing extra options to operations Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/working-with-cableready.md Pass additional JSON-compatible data to the client that is ignored by CableReady but accessible via life-cycle events. ```ruby cable_ready["user"].set_cookie( cookie: "favorite_food=pasta", foo: "bar" ).broadcast ``` -------------------------------- ### Using selector as an optional first argument Source: https://github.com/stimulusreflex/cable_ready/blob/main/docs/guide/working-with-cableready.md Specify the target element as the first parameter to DOM-mutating operations to reduce code verbosity. ```ruby cable_ready .inner_html("#red", html: "Red wins!") ```