I am implementing a chat in Rails 5 API Action Cable using Devise and gem 'devise_token_auth'.
I have a ChatRequestChannel
with parameterized subscriptions:
stream_from "chat_request_#{chat_request_chanel_token}_channel"
I need to somehow reliably retrieve the chat_request_chanel_token
value inside the unsubscribed
hook - to send a message to other subscribers. Here's my code:
class ChatRequestChannel < ApplicationCable::Channel
def subscribed
answerer = params["answerer"]
chat_request_chanel_token = answerer
answerer_user = User.find_by email: answerer
if answerer_user
stream_from "chat_request_#{chat_request_chanel_token}_channel"
else
# http://api.rubyonrails.org/classes/ActionCable/Channel/Base.html#class-ActionCable::Channel::Base-label-Rejecting+subscription+requests
reject
end
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
chat_request_chanel_token = "What to put here????"
message = "Client disconnected"
ActionCable.server.broadcast "chat_request_#{chat_request_chanel_token}_channel",
disconnected: message
end
end
All the clients subscribe to ChatRequestChannel
and with the command like this (answerer
param varies from client to client):
{"command":"subscribe","identifier":"{\"channel\":\"ChatRequestChannel\",\"answerer\":\"client1@example.com\"}"}
The unsubscribed
hook actually gets called when a client disconnects from Action Cable. So I can't provide any params to unsubscribed
.
I suggest that every client should have only one (per parameter) parameterized subscription to the ChatRequestChannel
. Is it stored somewhere inside Action Cable and can be retrieved?