Document Action Cable Channel Callbacks

This commit is contained in:
Svyatoslav Kryukov 2022-06-27 09:55:34 +03:00
parent fb9e9ef5d7
commit b66df44f1f
No known key found for this signature in database
GPG Key ID: E1EB3B4F3AE95534
2 changed files with 48 additions and 0 deletions

View File

@ -4,6 +4,22 @@ require "active_support/callbacks"
module ActionCable
module Channel
# = Action Cable Channel Callbacks
#
# Action Cable Channel provides hooks during the life cycle of a channel subscription.
# Callbacks allow triggering logic during this cycle. Available callbacks are:
#
# * <tt>before_subscribe</tt>
# * <tt>after_subscribe</tt> (also aliased as: <tt>on_subscribe</tt>)
# * <tt>before_unsubscribe</tt>
# * <tt>after_unsubscribe</tt> (also aliased as: <tt>on_unsubscribe</tt>)
#
# NOTE: the <tt>after_subscribe</tt> callback is triggered whenever
# the <tt>subscribed</tt> method is called, even if subscription was rejected
# with the <tt>reject</tt> method.
# To trigger <tt>after_subscribe</tt> only on successful subscriptions,
# use <tt>after_subscribe :my_method_name, unless: :subscription_rejected?</tt>
#
module Callbacks
extend ActiveSupport::Concern
include ActiveSupport::Callbacks

View File

@ -234,6 +234,38 @@ class ChatChannel < ApplicationCable::Channel
end
```
#### Channel Callbacks
`ApplicationCable::Channel` provides a number of callbacks that can be used to trigger logic
during the life cycle of a channel. Available callbacks are:
- `before_subscribe`
- `after_subscribe` (also aliased as: `on_subscribe`)
- `before_unsubscribe`
- `after_unsubscribe` (also aliased as: `on_unsubscribe`)
NOTE: The `after_subscribe` callback is triggered whenever the `subscribed` method is called,
even if subscription was rejected with the `reject` method. To trigger `after_subscribe`
only on successful subscriptions, use `after_subscribe :send_welcome_message, unless: :subscription_rejected?`
```ruby
# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
after_subscribe :send_welcome_message, unless: :subscription_rejected?
after_subscribe :track_subscription
private
def send_welcome_message
broadcast_to(...)
end
def track_subscription
# ...
end
end
```
## Client-Side Components
### Connections