mcpField
A
action-cable

action-cable

github.com/rolemodel开发738 次安装1 天前更新
代码仓库

关于 action-cable

为 Rails 应用提供 ActionCable 设置指南,涵盖 WebSocket 连接认证、频道配置与 Turbo Streams 广播,适合实现实时更新的开发者。

主要功能

  1. 01配置 ActionCable 连接与频道
  2. 02通过 Devise/Warden 验证连接
  3. 03使用 Turbo Streams 广播更新
  4. 04设置 Cable 适配器与路由
  5. 05检查连接状态并启用日志

适用场景

  1. 01为应用添加实时通知
  2. 02按组织范围广播计时器更新
  3. 03排查 WebSocket 连接问题

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/rolemodel/rolemodel-skills --skill action-cable

安装后在 Claude Code 中输入/action-cable确认已加载。

详细介绍

ActionCable 设置

概述

ActionCable 将 WebSocket 与 Rails 集成,以支持实时功能。本指南介绍此应用中的基本设置。

核心组件

1. 连接(app/channels/application_cable/connection.rb)

连接使用 Devise/Warden 对 WebSocket 连接进行身份验证和授权。

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    private

    def find_verified_user
      if verified_user = env['warden'].user
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end
2. 通道(app/channels/application_cable/channel.rb)

所有应用通道的基类。

module ApplicationCable
  class Channel < ActionCable::Channel::Base
  end
end
3. JavaScript 设置(app/javascript/initializers/actioncable.js)

在客户端初始化 ActionCable consumer。

import * as ActionCable from '@rails/actioncable'

ActionCable.logger.enabled = false

广播更新

使用 Turbo Streams(推荐)

在视图中订阅流:

= turbo_stream_from record
= turbo_stream_from [record, "channel_name"]

从控制器或后台任务广播 Turbo Stream 更新:

# Append content to a target
Turbo::StreamsChannel.broadcast_append_to(
  [record, "channel_name"],
  target: "dom_id",
  partial: "path/to/partial",
  locals: { record: record }
)

# Replace content
Turbo::StreamsChannel.broadcast_replace_to(
  [record, "channel_name"],
  target: "dom_id",
  partial: "path/to/partial",
  locals: { record: record }
)

# Remove element
Turbo::StreamsChannel.broadcast_remove_to(
  [record, "channel_name"],
  target: "dom_id"
)
示例:按组织范围限定的通知

视图:

= turbo_stream_from current_organization, "timers"

#notifications

控制器:

def start_timer
  # ... create timer logic ...

  Turbo::StreamsChannel.broadcast_append_to(
    [current_organization, "timers"],
    target: "notifications",
    partial: "timers/notification",
    locals: { timer: @timer }
  )
end

配置

Cable URL(config/cable.yml)
development:
  adapter: async

test:
  adapter: test

production:
  adapter: solid_cable
  connects_to:
    database:
      writing: cable
  polling_interval: 0.1.seconds
  message_retention: 1.day
路由(config/routes.rb)

ActionCable 会自动挂载到 /cable:

Rails.application.routes.draw do
  mount ActionCable.server => '/cable'
end

调试

在开发环境中启用日志记录:

// app/javascript/initializers/actioncable.js
ActionCable.logger.enabled = true

检查连接状态:

const subscription = consumer.subscriptions.create("ExampleChannel", {
  connected() {
    console.log("Connected to ExampleChannel")
  }
})

console.log(subscription)

安全注意事项

  • 始终在 ApplicationCable::Connection 中对连接进行身份验证
  • 验证通道订阅中的参数
  • 尽可能使用 stream_for 而不是 stream_from,以自动限定范围
  • 切勿在未经验证的情况下信任客户端数据
  • 对接受客户端消息的通道,可考虑进行速率限制

评论

支持 Markdown