I am trying to create sort of Whatsapp like messaging app server side in Rails, with private conversations. now, I am trying to implement the realtime part of the app - I am using websocket-rails - and I am not sure how to send a message only to the users in the private message - I saw a feature called private channels in websocket-rails - but after reading the documentation, I got under the impression that each private channel needs to be defined statically, and I cannot create channels realtime. Do you know how can I implement private conversations in websocket-rails, like a guide or a direction? or any other websocket service I can use to implement it?
You can pass parameters from the client side to the server side when creating a subscription. For example:
# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from "chat_#{params[:room]}"
end
end
An object passed as the first argument to subscriptions.create becomes the params hash in the cable channel. The keyword channel is required:
# app/assets/javascripts/cable/subscriptions/chat.coffee
App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
received: (data) ->
@appendLine(data)
appendLine: (data) ->
html = @createLine(data)
$("[data-chat-room='Best Room']").append(html)
createLine: (data) ->
"""
<article class="chat-line">
<span class="speaker">#{data["sent_by"]}</span>
<span class="body">#{data["body"]}</span>
</article>
"""
Somewhere in your app this is called, perhaps
ActionCable.server.broadcast(
"chat_#{room}",
sent_by: 'Paul',
body: 'This is a cool chat app.'
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.