Ruby on rails 5 有了ActionCable,有没有办法计算一个频道内有多少用户?

Ruby on rails 5 有了ActionCable,有没有办法计算一个频道内有多少用户?,ruby-on-rails-5,actioncable,Ruby On Rails 5,Actioncable,对于我正在构建的应用程序,我有一个“大厅”页面,人们可以在其中配置他们想要加入的区域。非常基本 我希望有一个当前订阅此页面频道的活跃消费者总数,以便用户知道周围是否有其他人可以与之交互 有没有一种简单的方法可以做到这一点?是的,有一种方法: 在你的app/channel/what_so_____称之为_it.rb的内容中: class WhatSoEverYouCalledItChannel < ApplicationCable::Channel def subscribed

对于我正在构建的应用程序,我有一个“大厅”页面,人们可以在其中配置他们想要加入的区域。非常基本

我希望有一个当前订阅此页面频道的活跃消费者总数,以便用户知道周围是否有其他人可以与之交互

有没有一种简单的方法可以做到这一点?

是的,有一种方法:

在你的app/channel/what_so_____称之为_it.rb的内容中:

class WhatSoEverYouCalledItChannel < ApplicationCable::Channel
     def subscribed
       stream_from "your_streamer_thingy"
       @subscriber +=1 #<==== like this
     end

     def unsubscribed
       # Any cleanup needed when channel is unsubscribed 
       @subscriber -=1 #<===== like this
     end
     def send_message(data)
        your_message_mechanic
     end
class whatsoeveryyoucalleditchannel@subscriber+=1#我定义了一个助手方法:

app/channels/application\u cable/channel.rb

module ApplicationCable
  class Channel < ActionCable::Channel::Base

    def connections_info

        connections_array = []

        connection.server.connections.each do |conn|

            conn_hash = {}

            conn_hash[:current_user] = conn.current_user

            conn_hash[:subscriptions_identifiers] = conn.subscriptions.identifiers.map {|k| JSON.parse k}

            connections_array << conn_hash

        end

        connections_array

    end

  end
end
然后,您可以按照所需的方式解析此结构并提取所需的数据。您可以通过相同的
current\u user
current\u user
方法在
class Channel
中提供)来区分此列表中的您自己的连接


如果用户连接两次(或更多次),则相应的数组元素只会加倍。

可能还有其他一些js方式或事件ruby的方式(这是第一个想法;)。我实际上是想直接在咖啡文件中完成,我会在这里发布解决方案,如果可行的话我知道这是很久以前的事了,但是@plombix你找到咖啡文件解决方案了吗?另外,在哪里实例化subscriber变量,因为这显然会抛出一个错误,除非首先在某个地方定义了subscriber…对我来说,
conn.current_user
返回为
nil
@sscirrus,
[1] pry(#<ChatChannel>)> connections_info
=> [{:current_user=>"D8pg2frw5db9PyHzE6Aj8LRf",
  :subscriptions_identifiers=>
   [{"channel"=>"ChatChannel",
     "secret_chat_token"=>"f5a6722dfe04fc883b59922bc99aef4b5ac266af"},
    {"channel"=>"AppearanceChannel"}]},
 {:current_user=>
   #<User id: 2, email: "client1@example.com", created_at: "2017-03-27 13:22:14", updated_at: "2017-04-28 11:13:37", provider: "email", uid: "client1@example.com", first_name: "John", active: nil, last_name: nil, middle_name: nil, email_public: nil, phone: nil, experience: nil, qualification: nil, price: nil, university: nil, faculty: nil, dob_issue: nil, work: nil, staff: nil, dob: nil, balance: nil, online: true>,
  :subscriptions_identifiers=>
   [{"channel"=>"ChatChannel",
     "secret_chat_token"=>"f5a6722dfe04fc883b59922bc99aef4b5ac266af"}]}]