Skip to content

Commit b66df44

Browse files
committed
Document Action Cable Channel Callbacks
1 parent fb9e9ef commit b66df44

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

actioncable/lib/action_cable/channel/callbacks.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,22 @@
44

55
module ActionCable
66
module Channel
7+
# = Action Cable Channel Callbacks
8+
#
9+
# Action Cable Channel provides hooks during the life cycle of a channel subscription.
10+
# Callbacks allow triggering logic during this cycle. Available callbacks are:
11+
#
12+
# * <tt>before_subscribe</tt>
13+
# * <tt>after_subscribe</tt> (also aliased as: <tt>on_subscribe</tt>)
14+
# * <tt>before_unsubscribe</tt>
15+
# * <tt>after_unsubscribe</tt> (also aliased as: <tt>on_unsubscribe</tt>)
16+
#
17+
# NOTE: the <tt>after_subscribe</tt> callback is triggered whenever
18+
# the <tt>subscribed</tt> method is called, even if subscription was rejected
19+
# with the <tt>reject</tt> method.
20+
# To trigger <tt>after_subscribe</tt> only on successful subscriptions,
21+
# use <tt>after_subscribe :my_method_name, unless: :subscription_rejected?</tt>
22+
#
723
module Callbacks
824
extend ActiveSupport::Concern
925
include ActiveSupport::Callbacks

guides/source/action_cable_overview.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,38 @@ class ChatChannel < ApplicationCable::Channel
234234
end
235235
```
236236

237+
#### Channel Callbacks
238+
239+
`ApplicationCable::Channel` provides a number of callbacks that can be used to trigger logic
240+
during the life cycle of a channel. Available callbacks are:
241+
242+
- `before_subscribe`
243+
- `after_subscribe` (also aliased as: `on_subscribe`)
244+
- `before_unsubscribe`
245+
- `after_unsubscribe` (also aliased as: `on_unsubscribe`)
246+
247+
NOTE: The `after_subscribe` callback is triggered whenever the `subscribed` method is called,
248+
even if subscription was rejected with the `reject` method. To trigger `after_subscribe`
249+
only on successful subscriptions, use `after_subscribe :send_welcome_message, unless: :subscription_rejected?`
250+
251+
```ruby
252+
# app/channels/chat_channel.rb
253+
class ChatChannel < ApplicationCable::Channel
254+
after_subscribe :send_welcome_message, unless: :subscription_rejected?
255+
after_subscribe :track_subscription
256+
257+
private
258+
259+
def send_welcome_message
260+
broadcast_to(...)
261+
end
262+
263+
def track_subscription
264+
# ...
265+
end
266+
end
267+
```
268+
237269
## Client-Side Components
238270

239271
### Connections

0 commit comments

Comments
 (0)