or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

connection-management.mdindex.mdjavascript-client.mdrails-integration.mdserver-broadcasting.mdsubscription-adapters.md
tile.json

server-broadcasting.mddocs/

Server Broadcasting

Server broadcasting provides the core functionality for sending messages to channel subscribers. It includes both direct broadcasting methods and reusable broadcaster instances for high-throughput scenarios.

Capabilities

ActionCable Server Access

Access the singleton server instance for broadcasting operations.

module ActionCable
  # Returns the singleton ActionCable server instance
  def self.server
    @server ||= ActionCable::Server::Base.new
  end
end

Usage Example:

# Get server instance
server = ActionCable.server

# Use for broadcasting
server.broadcast("notifications_123", { title: "New Message" })

Server Broadcasting Methods

Core broadcasting functionality on the server instance.

class ActionCable::Server::Base
  # Broadcast a hash directly to a named broadcasting
  # @param broadcasting [String] The channel name to broadcast to
  # @param message [Hash] The message data to send
  # @param coder [Object] Optional JSON encoder (defaults to ActiveSupport::JSON)
  def broadcast(broadcasting, message, coder: ActiveSupport::JSON)
  end
  
  # Returns a broadcaster for a named broadcasting that can be reused
  # @param broadcasting [String] The channel name
  # @param coder [Object] Optional JSON encoder
  # @return [ActionCable::Server::Broadcasting::Broadcaster]
  def broadcaster_for(broadcasting, coder: ActiveSupport::JSON)
  end
end

Usage Examples:

# Direct broadcasting
ActionCable.server.broadcast("chat_room_1", {
  message: "Hello everyone!",
  user_id: 123,
  timestamp: Time.current
})

# Reusable broadcaster for high-frequency updates
broadcaster = ActionCable.server.broadcaster_for("live_feed_updates")
broadcaster.broadcast({ stock: "AAPL", price: 150.25 })
broadcaster.broadcast({ stock: "GOOGL", price: 2750.80 })

Broadcaster Instance

Reusable broadcaster instance for efficient repeated broadcasting to the same channel.

class ActionCable::Server::Broadcasting::Broadcaster
  # Initialize broadcaster for specific channel
  # @param server [ActionCable::Server::Base] Server instance
  # @param broadcasting [String] Channel name
  # @param coder [Object] JSON encoder
  def initialize(server, broadcasting, coder:)
  end
  
  # Broadcast message to the channel
  # @param message [Hash] Message data to broadcast
  def broadcast(message)
  end
  
  attr_reader :server, :broadcasting, :coder
end

Channel-level Broadcasting

Broadcasting functionality available within channel classes.

module ActionCable::Channel::Broadcasting
  extend ActiveSupport::Concern
  
  # Delegate broadcasting_for to class methods
  delegate :broadcasting_for, to: :class
  
  module ClassMethods
    # Broadcast a hash to a unique broadcasting for this model in this channel
    # @param model [Object] Model instance to broadcast to
    # @param message [Hash] Message data to broadcast
    def broadcast_to(model, message)
    end
    
    # Generate broadcasting name for model
    # @param model [Object] Model or array of models
    # @return [String] Broadcasting name
    def broadcasting_for(model)
    end
  end
end

Channel Implementation

Channel Base Class

Base class for all ActionCable channels providing subscription lifecycle and streaming capabilities.

class ActionCable::Channel::Base
  include ActionCable::Channel::Callbacks
  include ActionCable::Channel::PeriodicTimers
  include ActionCable::Channel::Streams
  include ActionCable::Channel::Naming
  include ActionCable::Channel::Broadcasting
  
  # Initialize channel with connection, identifier, and params
  def initialize(connection, identifier, params = {})
  end
  
  # Called when a client subscribes to the channel
  # Override in subclasses to handle subscription logic
  def subscribed
  end
  
  # Called when a client unsubscribes from the channel  
  # Override in subclasses to handle cleanup
  def unsubscribed
  end
  
  # Send data directly to the subscribed client
  # @param data [Hash] Data to transmit to client
  # @param via [String] Optional identifier for transmission method
  def transmit(data, via: nil)
  end
  
  # Reject the subscription attempt
  def reject
  end
  
  # Extract action name from data and process it
  # @param data [Hash] Action data from client
  def perform_action(data)
  end
  
  # Get all action methods for this channel class
  # @return [Set] Set of action method names
  def self.action_methods
  end
  
  # Access to connection instance
  attr_reader :connection
  
  # Access to subscription parameters
  attr_reader :params
  
  # Access to channel identifier
  attr_reader :identifier
  
  # Delegate logger to connection
  delegate :logger, to: :connection
end

Usage Examples:

class ChatChannel < ApplicationCable::Channel
  def subscribed
    # Stream from room-specific broadcasting
    stream_from "chat_#{params[:room_id]}"
    
    # Or stream for a specific model
    room = Room.find(params[:room_id])
    stream_for room
  end

  def unsubscribed
    # Cleanup when client disconnects
    stop_all_streams
  end

  def speak(data)
    # Broadcast to all room subscribers
    ActionCable.server.broadcast("chat_#{params[:room_id]}", {
      message: data['message'],
      user: current_user.name,
      timestamp: Time.current
    })
  end
  
  def typing(data)
    # Send typing indicator to other room subscribers
    broadcast_to_others({ type: 'typing', user: current_user.name })
  end
  
  private
  
  def broadcast_to_others(data)
    ActionCable.server.broadcast("chat_#{params[:room_id]}", data.merge({
      exclude_connection_id: connection.connection_identifier
    }))
  end
end

Channel Streaming Methods

Advanced streaming capabilities for channels.

module ActionCable::Channel::Streams
  extend ActiveSupport::Concern
  
  # Stream from a named broadcasting (included in Channel::Base)
  # @param broadcasting [String] The broadcasting name to stream from
  # @param callback [Proc] Optional callback for processing messages
  # @param coder [Object] Optional coder for decoding messages (defaults to nil)
  def stream_from(broadcasting, callback = nil, coder: nil, &block)
  end
  
  # Stream for a specific model instance (included in Channel::Base)
  # @param model [ActiveRecord::Base] Model instance to stream for
  # @param callback [Proc] Optional callback for processing messages  
  # @param coder [Object] Optional coder for decoding messages (defaults to nil)
  def stream_for(model, callback = nil, coder: nil, &block)
  end
  
  # Stop all active streams for this subscription
  def stop_all_streams
  end
  
  private
  
  # Delegate pubsub to connection
  delegate :pubsub, to: :connection
  
  # Get list of active streams
  def streams
  end
end

Periodic Timers

Set up periodic tasks within channels.

module ActionCable::Channel::PeriodicTimers
  extend ActiveSupport::Concern
  
  # Class attribute for storing periodic timer definitions
  included do
    class_attribute :periodic_timers, instance_reader: false, default: []
    after_subscribe   :start_periodic_timers
    after_unsubscribe :stop_periodic_timers
  end
  
  module ClassMethods
    # Set up a periodic timer for the channel
    # @param callback_or_method_name [Symbol, Proc] Method name or proc to call periodically
    # @param every [Numeric] Interval in seconds
    # @param block [Block] Block to execute if no callback provided
    def periodically(callback_or_method_name = nil, every:, &block)
    end
  end
  
  private
  
  # Get active periodic timers for this instance
  def active_periodic_timers
  end
  
  # Start all periodic timers
  def start_periodic_timers
  end
  
  # Stop all periodic timers
  def stop_periodic_timers
  end
end

Usage Example:

class StatusChannel < ApplicationCable::Channel
  periodically :send_heartbeat, every: 30.seconds
  
  def subscribed
    stream_from "status_updates"
  end
  
  private
  
  def send_heartbeat
    transmit({ type: 'heartbeat', timestamp: Time.current })
  end
end

Channel Callbacks

Callback system for handling channel lifecycle events.

module ActionCable::Channel::Callbacks
  extend ActiveSupport::Concern
  include ActiveSupport::Callbacks
  
  # Define subscribe and unsubscribe callbacks
  included do
    define_callbacks :subscribe
    define_callbacks :unsubscribe
  end
  
  module ClassMethods
    # Set before_subscribe callback
    # @param methods [Array<Symbol>] Method names to call
    # @param block [Block] Block to execute
    def before_subscribe(*methods, &block)
    end
    
    # Set after_subscribe callback
    # @param methods [Array<Symbol>] Method names to call  
    # @param block [Block] Block to execute
    def after_subscribe(*methods, &block)
    end
    alias_method :on_subscribe, :after_subscribe
    
    # Set before_unsubscribe callback
    # @param methods [Array<Symbol>] Method names to call
    # @param block [Block] Block to execute
    def before_unsubscribe(*methods, &block)
    end
    
    # Set after_unsubscribe callback
    # @param methods [Array<Symbol>] Method names to call
    # @param block [Block] Block to execute
    def after_unsubscribe(*methods, &block)
    end
    alias_method :on_unsubscribe, :after_unsubscribe
  end
end

Usage Example:

class ChatChannel < ApplicationCable::Channel
  before_subscribe :authenticate_user
  after_subscribe :join_room
  before_unsubscribe :leave_room
  
  def subscribed
    # Main subscription logic
    stream_from "chat_#{params[:room_id]}"
  end
  
  private
  
  def authenticate_user
    reject unless current_user&.can_join_chat?
  end
  
  def join_room
    ChatRoom.find(params[:room_id]).add_participant(current_user)
  end
  
  def leave_room
    ChatRoom.find(params[:room_id]).remove_participant(current_user)
  end
end