Rails动作电缆特定消费者

Ill*_*zma 3 ruby-on-rails actioncable

我正在努力使用动作电缆.在我的情况下,我有几个用户(via Devise)可以互相分享任务.

现在,当所有经过身份验证的用户user#1共享任务(通过表单)user#2接收通知时.

我应该如何以及在何处识别我user#2的广播?

到目前为止,这是我的代码:

connection.rb

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

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.id
    end

    protected

    def find_verified_user # this checks whether a user is authenticated with devise
      if verified_user = env['warden'].user
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

cable.js

(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer();

}).call(this);
Run Code Online (Sandbox Code Playgroud)

todo_channel.rb

class TodoChannel < ApplicationCable::Channel
  def subscribed
    stream_from "todo_channel_#{current_user.id}"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end


  def notify
    ActionCable.server.broadcast "todo_channel_#{current_user.id}", message: 'some message'(not implemented yet)
  end
end
Run Code Online (Sandbox Code Playgroud)

todo.coffee

App.todo = App.cable.subscriptions.create "TodoChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    console.log(data['message'])

  notify: ->
    @perform 'notify'
Run Code Online (Sandbox Code Playgroud)

小智 5

我之前遇到过类似的事情,直到我意识到你实际上可以stream_from在频道中多次呼叫 ,并且该用户将在同一频道连接中订阅多个不同的"房间".这意味着你基本上可以做到这一点

class TodoChannel < ApplicationCable::Channel
  def subscribed
    stream_from "todo_channel_all"                            
    stream_from "todo_channel_#{current_user.id}"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def notify(data)
    # depending on data given from the user, send it to only one specific user or everyone listening to the "todo_channel_all"
    if data['message']['other_user_id']
      ActionCable.server.broadcast "todo_channel_#{data['message']['other_user_id']}", message: 'some message'
    else
      ActionCable.server.broadcast "todo_channel_all", message: 'some message'
    end

  end
end
Run Code Online (Sandbox Code Playgroud)

该代码假设用户已经知道其他用户的id并将其发送到频道,你可能不得不用一些安全性或其他东西来包装,我承认我对rails的经验不是很充分,因为我还在学习.

在将来可能对您有益的其他事实是您还可以在同一个频道功能中广播多个消息/次.这意味着您可以支持将您的任务发送给单个特定用户,特定用户列表或每个人.只需迭代列表/数组/用户的任何内容,并在他们的个人"todo_channel _#{user.id}"中向他们广播任务/消息/通知/任何内容.