Private Messages with Faye and Rails

I use the faye gem tagged in railscast allows applications to enter messages. The problem is that it sends messages to all open chat clients. I need them to be private. You can receive private messages from faye, but it is based on the URL. For example, all messages will be sent to site.com/foo . But in my model, chat does not have a specific URL. Because chat is just a collection of messages sent to you by this user.

So, if you are logged in, since adam site.com/messages/eve will allow you to talk with the eve, but for him it's the other way around. site.com/messages/adam . So a specific private chat seems to be out of the question.

Any pointers?

messages_controller.rb (start ajax)

 def create @message = Message.new(message_params) @message.save end 

create.js.erb (call broadcast method)

 <% broadcast params[:message][:username] do %> $(".text-wrap").append("<%= current_user.name %> <%= @message.body %></div>"); <% end %> 

broadcast method (sending to faye server)

 def broadcast(user, &block) channel = "/messages/#{user}" message = {:channel => channel, :data => capture(&block)} uri = URI.parse("http://localhost:9292/faye") Net::HTTP.post_form(uri, :message => message.to_json) end 

application.js (faye server subscription to / messages / *)

 $(function(){ var faye = new Faye.Client('http://localhost:9292/faye'); var subscription = faye.subscribe('/messages/*', function(message) { eval(message); }); }); 
+4
source share
1 answer

I solved it! The problem was that I had a subscription function in application.js, meaning that it would run javascript on every page. Instead, I ended up at the bottom of the chat page on which I subscribed to /messages/eve/adam . Here is how I did it:

 <script> $(function(){ var faye = new Faye.Client('http://localhost:9292/faye'); var subscription = faye.subscribe('/messages/#{current_user.username}/#{@user.username}', function(message) { eval(message); }); }); </script> 

Then, in the broadcast method, I sent the information only to the right place.

 def broadcast(user, &block) channel = "/messages/#{current_user.username}/#{user}" message = {:channel => channel, :data => capture(&block)} uri = URI.parse("http://localhost:9292/faye") Net::HTTP.post_form(uri, :message => message.to_json) end 
+2
source

Source: https://habr.com/ru/post/1398130/


All Articles