2016-06-10 51 views
0

我有這樣的代碼:如何使用ActionCable一次性清晰地向多個頻道廣播?

ActionCable.server.broadcast "posts_#{self.post_id}", { object: some_object } 

我想這同樣的有效載荷發送到多個廣播中。在顯而易見的方法是通過廣播中的數組:

ActionCable.server.broadcast ["posts_#{self.post_id}", "all_posts"], \ 
    { object: some_object } 

但這似乎整個數組對待爲標識符:

[ActionCable] Broadcasting to ["posts_30453", "all_posts"]: ... 

而且,無論是廣播臨危消息。

看起來應該有一個更簡潔的方法來做到這一點,而不是多次撥打ActionCable.server.broadcast。在那兒?

回答

1

我建立了一個小幫手寶石(multicable)來做到這一點。它增加了一個broadcast_multiple方法ActionCable ::服務器:

> ActionCable.server.broadcast_multiple ["broadcasting1", "broadcasting2"], { payload: "whatever" } 
[ActionCable] Broadcasting to broadcasting1: {:payload=>"whatever"} 
[ActionCable] Broadcasting to broadcasting2: {:payload=>"whatever"} 

無論是安裝寶石(gem 'multicable'),或在項目中的某處拋出微小來源:

ActionCable::Server::Base.class_eval do 
    def broadcast_multiple(broadcastings, message, coder: ActiveSupport::JSON) 
    broadcastings.each do |broadcasting| 
     broadcast(broadcasting, message, coder: coder) 
    end 
    end 
end 
相關問題