I'm using private_pub as a gem for implementing a notification system much like the one Facebook provides. For that, I am subscribing to a channel in a View and publishing from various places (different Controllers).
What's happening is that sometimes I get a lot of publishes for a single subscription. Do you have any idea about why this could happen?
My first suspicion was that I might be calling my notify method too many times (in some kind of loop or something, but I can see that it is only being called once, so I guess the problem must be somewhere in between the pub/sub layer, and most likely because of something I am doing wrong when notifying the View.
Next I present some snippets of my implementation.
In the _header.html.erb partial of my website, I subscribe to the user's notification channel, like so:
For instance in my friendships_controller, when adding a friend I generate some html to present the notification and publish the jquery with the prepended notification, like so:
html_text = render_to_string(:partial => 'notifications/notification', :locals => { notification: notification }, :formats => [:html]).squish jquery = "$('#notifications_" + user.id.to_s + "').prepend('#{html_text}');" PrivatePub.publish_to("/notifications/" + user.id.to_s, jquery)
Sorry for the long post, I hope some of you can help me. Thanks in advance.
Btw, I am running Rails 4.0.0 with Ruby 2.0.0p247.
I've been getting this problem, too, I think... I suspect I'm multiply subscribing somehow, and I suspect it has something to do with Turbolinks. The extra subscriptions appear to pile up when you visit other pages without a full reload. Maybe some sort of cacheing?
I've come up with a sleazy workaround that does the job. Not a great solution, though, I'd rather know why the multiple subscribe is happening. Still, this pattern works to kill the problem.
Basically, just delete anything you're about to insert into the DOM before you add it. Usually this will be an object you've marked with a dom_id, but if you're inserting multiple things, it might be more convenient to add some class that lets you get them all.
Let's say you're creating some @object which has a partial that you're inserting into the dom, appending it to #some_destination. In your
create.js.slim
(convert mentally to erb/haml/etc if you must)and then in the partial
_object.html.slim
you make sure it's marked properlySleazy but it works. I would prefer to know why I'm getting these multiple subscriptions to the same channel and how to stop them, that would be much better than this workaround.