Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send message to all client except sender in rails/actioncable?

in socket.io, you can send message to all client except sender like:

socket.broadcast.emit('user connected');

but in rails/actioncable, how to do that?

class BoardChannel < ApplicationCable::Channel
   def subscribed
     stream_from "board:#{params[:board]}"
   end

   def speak
     # client will call @perform('speak')
     result = do_something()
     # how to send 'result' to all client except sender?
   end
 end
like image 915
xlaok Avatar asked Aug 11 '16 09:08

xlaok


2 Answers

I have been worrying about this problem all afternoon. All ready to give up, just lying in bed, my mind flashed a solution it works! ! ! Sign in to share

 class BoardChannel < ApplicationCable::Channel
   def subscribed
     stream_from "board:#{params[:board]}"
     stream_from "global_stream"
   end
 end

Then, when you want to broadcast all users, you can:

ActionCable.server.broadcast "global_stream", "some messages"

Of course, you can also broadcast to special users. you can:

ActionCable.server.broadcast "board:#{params[:board]}", "some messages"

Perfect!!!

like image 56
active_liang Avatar answered Sep 30 '22 15:09

active_liang


Using jobs, you can make this with the logic in a partial.
In your model after create a record, call the job perform passing the self record. See bellow how pass message to recieved data(at channel) using broadcast.

   ...  

   def perform(message)
     ActionCable.server.broadcast "board:#{params[:board]}",
     message: render_message(message)
   end

   private

   def 
     ApplicationController.renderer.render(
       partial: 'messages/message.html.erb',
       locals: { message: message }
     )
   end  

Create a partial in views/messages/_message.html.erb and in your code make

 <%= if message.sender_id == current_user.id %>
   The code to report that forwarded message.
 <%= else %>
   The code to send the message to all except sender.
 <% end %>
like image 29
Léo Rocha Avatar answered Sep 30 '22 17:09

Léo Rocha