How to close connection in Action cable?

Slesarenko Alexander picture Slesarenko Alexander · Nov 8, 2016 · Viewed 8.7k times · Source

How to disconnect a client in Action cable (rails 5)? I would like the user to be completely disconnected (similar to when he closes the tab).

Answer

prograils picture prograils · Apr 21, 2017

I found this inside /var/lib/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/remote_connections.rb

If you need to disconnect a given connection, you can go through the RemoteConnections. You can find the connections you're looking for by searching for the identifier declared on the connection. For example:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user
    ....
  end
end

ActionCable.server.remote_connections.where(current_user: User.find(1)).disconnect

This will disconnect all the connections established for
User.find(1), across all servers running on all machines, because it uses the internal channel that all of these servers are subscribed to.

Hope this will be useful. Looks like it works even in Rails console.