How to use Wisper with different instances of same Active Record Model?

180 Views Asked by At

I'm trying to use Wisper with Rails 4 / AR and encountering an issue.

Let's say I have Email and Creep AR models, and I want the Creep to know when a reply was received (Creep is not necessarily the sender...)

So I do:

email = Email.create! params
creep = Creep.last
email.subscribe(creep, on: :reply_received, with: :success)

and if immediately do:

email.publish :reply_received

It will work (Creep instances have a success method).

However, if i later do:

email = Email.find(id)

or:

email = Email.last

The event is not broadcast. I'm guessing this is because the new email is a different instance, and thus has no listeners subscribed. What am I doing wrong?

1

There are 1 best solutions below

2
Kris On

You are correct. Using email.subscribe you are subscribing the listener to a single object. When you do Email.find you get back a different email object (check email.object_id).

You can either subscribe creep to the newly returned object:

email = Email.find(id)
email.subscribe(Creep.last)

Or you could subscribe creep to all instances of Email like this:

 Email.subscribe(Creep.last)

You'll proberbly want to do the above in an initializer so it only happens once.

However this might be an issue because it seems you want to subscribe Creep.last which will change over time. In which case you can do something fancy like this:

class CreepListener
  def success(*args)
    Creep.last.success(*args)
  end
end

Email.subscribe(CreepListener.new)