0

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?

Kris
  • 19,188
  • 9
  • 91
  • 111
delight
  • 1
  • 1

1 Answers1

1

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)
Kris
  • 19,188
  • 9
  • 91
  • 111
  • Thanks. I'm currently using something like the latter suggestion (subscribing to all emails and finding the right creep for each email as it happens). The former solution would violate my goal (and one of the great advantages of Wisper in my eyes) of decoupling the Email/Creep code. / Do you see any advantage to having subscribe work differently for AR objects in the case we want all instances of the same model id to be considered the same? Perhaps a method on the Publisher class which allows the user to override the way the instance is stored/represened on subscribe? If so I'm happy to help. – delight Jun 26 '15 at 16:47
  • If you want to open an issue on Github with a code example of the issue I would be happy to discuss. I've not come across this problem before. – Kris Jun 29 '15 at 14:24