본문으로 건너뛰기
cccskills
무료GitHub에 공개

Action Cable & WebSocket Patterns

Real-time WebSocket features with Action Cable in Rails. Use when: (1) Building real-time chat, (2) Live notifications/presence, (3) Broadcasting model updates, (4) WebSocket authorization. Trigger keywords: Action Cable, WebSocket, real-time, channels, broadcasting, stream, subscriptions, presence, cable

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

연동 도구Redis
설치 방법 보기

포함된 파일(2)

  • SKILL.md6.7 KB
  • source.json854 B

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Action Cable Patterns

Real-time WebSocket features for Rails applications.

Real-Time Feature Decision Tree

What real-time feature?
│
├─ User notifications
│   └─ Personal stream: stream_from "notifications_#{current_user.id}"
│
├─ Chat room messages
│   └─ Group stream: stream_from "chat_room_#{room.id}"
│
├─ Model updates (live editing)
│   └─ Model stream: stream_for @post (with broadcast_to)
│
├─ Presence tracking (who's online)
│   └─ Presence stream + Redis: stream_from "presence_room_#{room.id}"
│
└─ Dashboard/analytics
    └─ Scoped stream: stream_from "dashboard_#{account.id}"

Core Principles (CRITICAL)

1. Authorization First

# WRONG - Security vulnerability!
def subscribed
  stream_from "private_data"  # Anyone can subscribe!
end

# RIGHT - Explicit authorization
def subscribed
  reject unless current_user
  reject unless current_user.can_access?(params[:resource_id])
  stream_from "private_#{params[:resource_id]}"
end

2. Persist First, Broadcast Second

# WRONG - Data lost if client offline
def speak(data)
  ActionCable.server.broadcast("chat", message: data['text'])
end

# RIGHT - Persist then broadcast
def speak(data)
  message = Message.create!(user: current_user, text: data['text'])
  ActionCable.server.broadcast("chat", message: message)
end

3. Use stream_for for Models

# WRONG - Manual naming (error-prone)
stream_from "posts:#{params[:id]}"
ActionCable.server.broadcast("posts:#{@post.id}", data)

# RIGHT - Type-safe model broadcasting
stream_for @post
PostChannel.broadcast_to(@post, data)

NEVER Do This

NEVER skip authorization:

# Every channel MUST have: reject unless current_user
# Plus resource-specific authorization

NEVER broadcast before commit:

# WRONG
post.save
ActionCable.server.broadcast(...)  # Transaction may rollback!

# RIGHT - Use after_commit callback
after_create_commit { broadcast_creation }

NEVER broadcast full objects:

# WRONG - Leaks data, slow
ActionCable.server.broadcast("posts", post: @post)

# RIGHT - Only needed fields
ActionCable.server.broadcast("posts", post: @post.as_json(only: [:id, :title]))

NEVER create subscriptions without cleanup (JavaScript):

// WRONG - Memory leak
consumer.subscriptions.create("ChatChannel", { ... })

// RIGHT - Cleanup on unmount
useEffect(() => {
  const sub = consumer.subscriptions.create(...)
  return () => sub.unsubscribe()
}, [])

Channel Template

class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    # 1. Authorization (REQUIRED)
    reject unless current_user

    # 2. Subscribe to stream
    stream_from "notifications_#{current_user.id}"
  end

  def unsubscribed
    # Cleanup (optional)
  end

  # Client action: channel.perform('mark_as_read', {id: 123})
  def mark_as_read(data)
    notification = current_user.notifications.find(data['id'])
    notification.mark_as_read!

    ActionCable.server.broadcast(
      "notifications_#{current_user.id}",
      action: 'count_updated',
      unread_count: current_user.notifications.unread.count
    )
  end
end

Stream Patterns Quick Reference

PatternUse CaseCode
PersonalNotificationsstream_from "user_#{current_user.id}"
ModelLive updatesstream_for @post → PostChannel.broadcast_to(@post, data)
GroupChat roomsstream_from "room_#{room.id}"
PresenceWho's onlinestream_from "presence_#{room.id}" + Redis

Broadcasting Patterns

From Model (Recommended)

class Post < ApplicationRecord
  after_create_commit { broadcast_creation }
  after_update_commit { broadcast_update }

  private

  def broadcast_creation
    PostChannel.broadcast_to(self, action: 'created', post: as_json(only: [:id, :title]))
  end
end

From Controller

def create
  @comment = @post.comments.create!(comment_params)
  CommentsChannel.broadcast_to(@post, action: 'created', comment: @comment.as_json)
end

From Background Job

class BroadcastJob < ApplicationJob
  def perform(channel_name, data)
    ActionCable.server.broadcast(channel_name, data)
  end
end

Connection Authentication

# app/channels/application_cable/connection.rb
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
      # Cookie auth (default Rails)
      if user = User.find_by(id: cookies.encrypted[:user_id])
        user
      # Token auth (API clients)
      elsif user = find_user_from_token
        user
      else
        reject_unauthorized_connection
      end
    end

    def find_user_from_token
      token = request.params[:token]
      return nil unless token
      payload = JWT.decode(token, Rails.application.secret_key_base).first
      User.find_by(id: payload['user_id'])
    rescue JWT::DecodeError
      nil
    end
  end
end

Testing Quick Reference

# spec/channels/notifications_channel_spec.rb
RSpec.describe NotificationsChannel, type: :channel do
  let(:user) { create(:user) }

  before { stub_connection(current_user: user) }

  it 'subscribes to user stream' do
    subscribe
    expect(subscription).to be_confirmed
    expect(subscription).to have_stream_from("notifications_#{user.id}")
  end

  it 'rejects unauthenticated users' do
    stub_connection(current_user: nil)
    subscribe
    expect(subscription).to be_rejected
  end

  it 'broadcasts on action' do
    subscribe
    expect {
      perform :mark_as_read, id: notification.id
    }.to have_broadcasted_to("notifications_#{user.id}")
  end
end

Production Config

# config/cable.yml
production:
  adapter: redis
  url: <%= ENV['REDIS_URL'] %>
  channel_prefix: myapp_production
# config/environments/production.rb
config.action_cable.url = ENV['ACTION_CABLE_URL']
config.action_cable.allowed_request_origins = ['https://example.com']

References

Detailed examples in references/:

  • javascript-consumers.md - Client-side subscription patterns
  • presence-tracking.md - Complete presence implementation with Redis
  • deployment.md - Nginx, scaling, production configuration

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

007

무료

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aibot88/sec_skill_store52026년 5월 27일 업데이트

Guides the creation of agile user stories and Gherkin feature files. Use when the user wants to create a user story, write acceptance criteria, define Gherkin scenarios, or author BDD feature files. This should trigger for requests such as Create a user story; Write a user story; I need to write a user story. Part of cursor-rules-java project

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aibot88/sec_skill_store52026년 5월 27일 업데이트

Facilitates conversational discovery to create Architectural Decision Records (ADRs) for non-functional requirements using the ISO/IEC 25010:2023 quality model. Use when the user wants to document quality attributes, NFR decisions, security/performance/scalability architecture, or design systems with measurable quality criteria. This should trigger for requests such as Create ADR for Non-functional requirements; Document Non-functional requirements; Capture Non-functional requirements; Generate Non-functional requirements in an ADR. Part of cursor-rules-java project

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aibot88/sec_skill_store52026년 5월 27일 업데이트

Run a health check on an existing project: dependency audit, security scan, test runner detection, CI/CD evaluation, and missing configuration analysis. Maps the three execution gates (pre/in/post) from /10x-bootstrapper to an assessment framework for existing codebases. Reads optional context/foundation/stack-assessment.md from /10x-stack-assess to focus checks on identified gaps. Writes context/foundation/health-check.md with findings, prioritized fixes, and an agent-readiness verdict. Use when the user has an existing project and wants to verify its health before working with an agent. Trigger phrases: "health check", "check my project", "audit my project", "is my project healthy", "sprawdź projekt", "audyt projektu", "health-check", "project health". Use AFTER /10x-stack-assess (brownfield chain), BEFORE agent onboarding (m1-l4).

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aibot88/sec_skill_store52026년 5월 27일 업데이트

10x-team

무료

You MUST use this when building projects end-to-end. Orchestrates all 12 team roles — automatically switches between CTO, architect, PM, engineers, SRE, security, DBA, QA, and EM based on the current phase of work. Starts with brainstorming before any implementation.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aibot88/sec_skill_store52026년 5월 27일 업데이트

Use when you need to add or configure Maven plugins in your pom.xml — including quality tools (enforcer, surefire, failsafe, jacoco, pitest, spotbugs, pmd), security scanning (OWASP), code formatting (Spotless), version management, container image build (Jib), build information tracking, and benchmarking (JMH) — through a consultative, modular step-by-step approach that only adds what you actually need. This should trigger for requests such as Add Maven plugins in pom.xml; Improve Maven plugins in pom.xml. Part of cursor-rules-java project

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aibot88/sec_skill_store52026년 5월 27일 업데이트

aibot88의 스킬 모두 보기

이 스킬의 문제 신고