动作电缆:在通道中调用自定义方法

Action cable : Call custom method in channel

我正在尝试实现动作电缆。这很好用,但我想在连接到频道时接收一些数据(这里我想知道有多少用户已连接)。

我在我的频道上创建了一个自定义方法 nbUsers :

class OnTheSamePageChannel < ApplicationCable::Channel

  @count = 0

  def subscribed
    ...
    @count++
    stream_for(params[:url])
  end

  def unsubscribed
    ...
    @count--
  end

  def nbUsers
    pp 'debug: nbUsersCalled'
    @count
  end

还有我的javascript:

export default class OnSamePageSubscription extends React.Component {

    constructor(props) {
        super(props);

        this.cable = ActionCable.createConsumer(WEB_SOCKET_HOST);
        this.subscribe = () => {
            this.channel = this.cable.subscriptions.create(
                {
                    channel: 'OnTheSamePageChannel',
                    url: props.url,
                    current_user: props.current_user
                },
                {
                    connected: this.connected,
                    disconnected: this.disconnected,
                    received: this.received,
                    rejected: this.rejected
                }
            );
        };
        this.unsubscribe = () => {
            this.channel.unsubscribe()
        };
    }

    received = (data) => {
        console.log(`Connected user : ${data.user}`);

        this.props.onUpdate(data);
    };

    connected = () => {
        console.log(`Tracking connection`);
    };

    disconnected = () => {
        console.warn(`Tracking disconnected.`);
    };

    rejected = () => {
        console.warn('Tracking rejected');
    };

}

问题是:如何调用此方法 (nbUsers) 并获取结果?

我试过了https://robots.thoughtbot.com/talking-to-actioncable-without-rails 但这不起作用

您可以使用 perform 调用它。这是代码 this.perform("nbUsers")

class OnTheSamePageChannel < ApplicationCable::Channel

  @count = 0

  def subscribed
    # ...
    @count++
    stream_for(params[:url])
    transmit(number_of_users: nbUsers)
  end
  # ...
end


export default class OnSamePageSubscription extends React.Component {
  // ...
  received = (data) => {
    console.log(`Number of users: ${data.number_of_users}`);

    this.props.onUpdate(data);
  };
}
  • 以上是对您问题的直接回答...

    how to call this method (nbUsers) and getting result ?

    ...但是,您当前的代码中仍然存在很多问题:

    • class OnTheSamePageChannel < ApplicationCable::Channel
        @count = 0 
        # ^ this is a class-level instance-variable
        # ...and not an instance-level instance-variable (that I think you were under the impression of
      end
      
      # To demonstrate:
      # OnTheSamePageChannel.new.instance_variable_get(:@count)
      # => nil
      # OnTheSamePageChannel.instance_variable_get(:@count)
      # => 0
      
    • 要解决此问题,您需要执行以下操作:

      class OnTheSamePageChannel < ApplicationCable::Channel
        attr_accessor :count
        @count = 0 
      
        def subscribed
          # ...
          self.class.count += 1
        end
      
        def unsubscribed 
          # ...
          self.class.count -= 1
        end
      
        def nbUsers
          # ...
          self.class.count
        end
      end
      
    • 重要提示:上面的代码只能在单进程服务器上工作,如果你已经有多个服务器或进程,或者其他 rails 依赖的应用程序,它就不会完全工作像 Sidekiq 或 (rails-console) 正是因为它们之间不共享内存(存储了 @count)。据我所知,如果 "scaling" 已经被考虑在内,还没有(还?)一种简单的内置 Rails 方法来检查连接用户的数量。随意检查一些其他