Actioncable connected users list

戏子无情 提交于 2019-12-01 10:32:15

Ya kinda have to roll your own user-tracking.

The important bits are as follows:

# connection
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :uid

    def connect
      self.uid = get_connecting_uid
      logger.add_tags 'ActionCable', uid
    end

    protected

    # the connection URL to this actioncable/channel must be
    # domain.tld?uid=the_uid
    def get_connecting_uid
      # this is just how I get the user id, you can keep using cookies,
      # but because this key gets used for redis, I'd 
      # identify_by the user_id instead of the current_user object
      request.params[:uid]
    end
  end
end


# Your Channel
def subscribed
  stop_all_streams
  stream_from broadcasting_name
  ConnectedList.add(uid)
end

def unsubscribed
  ConnectedList.remove(uid)
end

And then in Models:

class ConnectedList
  REDIS_KEY = 'connected_nodes'

  def self.redis
    @redis ||= ::Redis.new(url: ActionCableConfig[:url])
  end

  # I think this is the method you want.
  def self.all
    redis.smembers(REDIS_KEY)
  end

  def self.clear_all
    redis.del(REDIS_KEY)
  end

  def self.add(uid)
    redis.sadd(REDIS_KEY, uid)
  end

  def self.include?(uid)
    redis.sismember(REDIS_KEY, uid)
  end

  def self.remove(uid)
    redis.srem(REDIS_KEY, uid)
  end
end

from: https://github.com/NullVoxPopuli/mesh-relay/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!