Rails pub/sub with faye

后端 未结 1 530
长情又很酷
长情又很酷 2021-02-02 03:01

In a Rails app I\'ve used Faye (Rack adapter) for push notifications (for chat).

I want to use Faye for another use case (more push notifications) but I can\'t seem to f

1条回答
  •  -上瘾入骨i
    2021-02-02 03:48

    First of all, yes, publishing the notification with after_create is fine. What you should do in your notify_subscribers method is to publish all relevant information about the new post that you want to use in the client so that you don't have to make another unnecessary AJAX request when the notification is received.

    So, for instance, if the title and content of the post are relevant for the user to see immediately after it gets created, you would do something like:

    def notify_subscribers
      client = Faye::Client.new('http://localhost:3000/faye')
      client.publish("/posts/new", {
        'title' => self.title,
        'content' => self.content
      })
    end
    

    ...and then, in the view, you would probably use jQuery to use the data about the new post which you receive from the server. Rails code won't help you here. E.g. you would do this (assuming you're using jQuery and have included faye.js in your header):

    
    

    Finally, if somehow the information you want to transfer is too complex to transfer as part of the notification, or you already have existing AJAX processes for updating your view, you could just publish the post's ID and trigger an AJAX call with jQuery in the subscribe callback function. I'd recommend this only if necessary though.

    0 讨论(0)
提交回复
热议问题