rails 5中的broadcast,broadcast_to和broadcast_for之间的区别

Imr*_*qvi 5 ruby ruby-on-rails ruby-on-rails-5

Rails Guide中,我发现了以下三个代码段

ActionCable.server.broadcast("chat_#{params[:room]}", data)
Run Code Online (Sandbox Code Playgroud)

这个简单的广播将数据发送到特定的聊天室

broadcast_to如下所示,似乎到当前用户订阅的信道内发送数据的所有聊天室。

WebNotificationsChannel.broadcast_to(
  current_user,
  title: 'New things!',
  body: 'All the news fit to print'
) 
Run Code Online (Sandbox Code Playgroud)

这是另一种广播的broadcast_for-我无法得到任何例子。

我的问题是这三个之间的实际区别是什么以及何时使用每个'em-预先感谢

squ*_*ism 4

broadcasting_for返回一个可以重用的对象。这对于在代码/时间的不同点向同一房间发送多条消息非常有用。 broadcast最终调用broadcasting_for,所以基本上是一样的。

broadcast_to脱离频道类别。您可以在创建频道后使用它。假设您想通知所有博客文章评论的订阅者。那么您的频道将类似于以下示例:

class CommentsChannel < ApplicationCable::Channel
  def subscribed
    post = Post.find(params[:id])
    stream_for post
  end
end
# use CommentsChannel.broadcast_to(@post, @comment)
Run Code Online (Sandbox Code Playgroud)

但是,如果您想向特定用户发送更多定向消息,那么您可以有一个名为EmailNotifications“只关心特定用户”的类。

class EmailNotificationsChannel < ApplicationCable::Channel
  ...

EmailNotificationsChannel.broadcast_to(
  current_user,
  title: 'You have mail!',
  body: data[:email_preview]   # some assumption of passed in or existing data hash here
)
Run Code Online (Sandbox Code Playgroud)