Module: Rage::Cable

Defined in:
lib/rage/cable/cable.rb

Overview

Rage::Cable provides built-in WebSocket support for Rage apps, similar to Action Cable in Rails. It lets you mount a separate WebSocket application, define channels and connections, subscribe clients to named streams, and broadcast messages in real time.

Define a channel:

class ChatChannel < Rage::Cable::Channel
  def subscribed
    stream_from "chat"
  end

  def receive(data)
    puts "Received message: #{data['message']}"
  end
end

Mount the Cable application:

Rage.routes.draw do
  mount Rage::Cable.application, at: "/cable"
end

Broadcast a message to a stream:

Rage.cable.broadcast("chat", { message: "Hello, world!" })

Defined Under Namespace

Modules: Adapters, Protocols Classes: Channel, Connection, Router, WebSocketConnection

Constant Summary collapse

Protocol =
Protocols

Class Method Summary collapse

Class Method Details

.applicationObject

Create a new Cable application.

Examples:

map "/cable" do
  run Rage.cable.application
end


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rage/cable/cable.rb', line 38

def self.application
  # explicitly initialize the adapter
  __adapter

  handler = __build_handler(__protocol)
  accept_response = [0, __protocol.protocol_definition, []]

  application = ->(env) do
    if env["rack.upgrade?"] == :websocket
      env["rack.upgrade"] = handler
      accept_response
    else
      [426, { "Connection" => "Upgrade", "Upgrade" => "websocket" }, []]
    end
  end

  Rage.with_middlewares(application, Rage.config.cable.middlewares)
end

.broadcast(stream, data) ⇒ true

Broadcast data directly to a named stream.

Examples:

Rage.cable.broadcast("chat", { message: "A new member has joined!" })

Parameters:

  • stream (String)

    the name of the stream

  • data (Object)

    the object to send to the clients. This will later be encoded according to the protocol used.

Returns:

  • (true)


135
136
137
138
139
140
# File 'lib/rage/cable/cable.rb', line 135

def self.broadcast(stream, data)
  __protocol.broadcast(stream, data)
  __adapter&.publish(stream, data)

  true
end