Loading...
Loading...
Setup and use ActionCable for real-time features in Rails applications using WebSockets. Use when implementing real-time updates, live notifications, broadcasting changes, or when the user mentions WebSockets, ActionCable, channels, broadcasting, or Turbo Streams over cable.
npx skill4agent add rolemodel/rolemodel-skills action-cableapp/channels/application_cable/connection.rbmodule 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
endapp/channels/application_cable/channel.rbmodule ApplicationCable
class Channel < ActionCable::Channel::Base
end
endapp/javascript/initializers/actioncable.jsimport * as ActionCable from '@rails/actioncable'
ActionCable.logger.enabled = false= turbo_stream_from record
= turbo_stream_from [record, "channel_name"]# 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"
#notificationsdef start_timer
# ... create timer logic ...
Turbo::StreamsChannel.broadcast_append_to(
[current_organization, "timers"],
target: "notifications",
partial: "timers/notification",
locals: { timer: @timer }
)
endconfig/cable.ymldevelopment:
adapter: async
test:
adapter: test
production:
adapter: solid_cable
connects_to:
database:
writing: cable
polling_interval: 0.1.seconds
message_retention: 1.dayconfig/routes.rb/cableRails.application.routes.draw do
mount ActionCable.server => '/cable'
end// app/javascript/initializers/actioncable.js
ActionCable.logger.enabled = trueconst subscription = consumer.subscriptions.create("ExampleChannel", {
connected() {
console.log("Connected to ExampleChannel")
}
})
console.log(subscription)ApplicationCable::Connectionstream_forstream_from