Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate subscription to an actioncable channel from server?

Is there a way to terminate the subscription to a particular channel for any particular consumer from the server side (controller) so that disconnected callback in my coffee script file can be invoked?

like image 966
Sambit Dutta Avatar asked Oct 02 '16 08:10

Sambit Dutta


1 Answers

http://api.rubyonrails.org/classes/ActionCable/Channel/Base.html#class-ActionCable::Channel::Base-label-Rejecting+subscription+requests

class ChatChannel < ApplicationCable::Channel
  def subscribed
    @room = Chat::Room[params[:room_number]]
    reject unless current_user.can_access?(@room)
  end
end

Before calling reject you can also inform the subscriber of the reject's reason:

class ChatChannel < ApplicationCable::Channel
  def subscribed

    if params["answerer"]

      answerer = params["answerer"]

      answerer_user = User.find_by email: answerer

      if answerer_user

        stream_from "chat_#{answerer_user}_channel"    

      else

        connection.transmit identifier: params, error: "The user #{answerer} not found."

  # http://api.rubyonrails.org/classes/ActionCable/Channel/Base.html#class-ActionCable::Channel::Base-label-Rejecting+subscription+requests

        reject

      end

    else

        connection.transmit identifier: params, error: "No params specified."

  # http://api.rubyonrails.org/classes/ActionCable/Channel/Base.html#class-ActionCable::Channel::Base-label-Rejecting+subscription+requests

        reject

    end     

  end
end
like image 126
prograils Avatar answered Oct 22 '22 02:10

prograils