/reactree-rails-dev:action-cable-patternsfrom reactree-rails-dev
Provides patterns for Action Cable WebSocket features in Rails: real-time chat, live notifications, presence tracking, and model broadcasting with authorization.
Ships in reactree-rails-dev. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Real-time WebSocket features for Rails applications.
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}"
# 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
# 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
# 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 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()
}, [])
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
| Pattern | Use Case | Code |
|---|---|---|
| Personal | Notifications | stream_from "user_#{current_user.id}" |
| Model | Live updates | stream_for @post → PostChannel.broadcast_to(@post, data) |
| Group | Chat rooms | stream_from "room_#{room.id}" |
| Presence | Who's online | stream_from "presence_#{room.id}" + Redis |
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
def create
@comment = @post.comments.create!(comment_params)
CommentsChannel.broadcast_to(@post, action: 'created', comment: @comment.as_json)
end
class BroadcastJob < ApplicationJob
def perform(channel_name, data)
ActionCable.server.broadcast(channel_name, data)
end
end
# 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
# 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
# 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']
Detailed examples in references/:
javascript-consumers.md - Client-side subscription patternspresence-tracking.md - Complete presence implementation with Redisdeployment.md - Nginx, scaling, production configurationWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
action-cable, websockets, real-time, rails-channels, live-updates
npx claudepluginhub kaakati/rails-enterprise-dev --plugin reactree-rails-dev26 skills in this plugin
/accessibility-patternsAccessibility PatternsWCAG 2.2 Level AA compliance for Rails/ViewComponent/Hotwire. Use when: (1) Building interactive widgets, (2) Handling form validation errors, (3) Adding dynamic content with Turbo Streams, (4) Auditing existing components. Trigger keywords: accessibility, a11y, WCAG, ARIA, screen reader, keyboard, focus, contrast/activerecord-patternsActiveRecord Query PatternsComplete guide to ActiveRecord query optimization, associations, scopes, and PostgreSQL-specific patterns. Use when: (1) Writing database queries, (2) Designing model associations, (3) Creating migrations, (4) Optimizing query performance, (5) Debugging N+1 queries and GROUP BY errors. Trigger keywords: database, models, associations, validations, queries, ActiveRecord, scopes, migrations, N+1, PostgreSQL, indexes, eager loading/api-development-patternsAPI Development PatternsComprehensive guide to building production-ready REST APIs in Rails with serialization, authentication, versioning, rate limiting, and testing. Trigger keywords: REST API, JSON, serialization, versioning, authentication, JWT, rate limiting, API controllers, request specs, API testing, endpoints, responsesOther plugins' skills for the same job