I'm trying t开发者_运维技巧o have a rails model observe another object (which acts as a subject). I saw that there is an update
method (which has different semantics) in ActiveRecord::Base
, but in order to use the Observable
module, I need to implement an update
method in my model so that I can be notified of changes to the subject.
Any thoughts on how this could be achieved?
You probably want to use a regular Observer which will receive event callbacks when something happens to the observed model.
Why do you need to encapsulate your observer functionality into another model?
You're better off putting the events/callbacks in your observer and calling any needed functionality as a helper method on the other model instead of making your model an observer.
EDIT: Adding example code
class User < ActiveRecord::Base
end
class UserObserver < ActiveRecord::Observer
observe :user
def after_save(user)
MyHelperClass.do_some_stuff_for_user(user)
end
end
class MyHelperClass
def self.do_some_stuff_for_user(user)
puts "OMG I just found out #{user.name} was saved so I can do stuff"
end
end
It appears that you can override the default update
that comes with ActiveRecord
, so that it can receive notifications from subjects (assuming you have mixed in Observable). The procedure for doing something like this is in the book "Pro ActiveRecord" published by APress (Chap. 5, "Bonus Features").
It involves the use of alias_method
/ alias_method_chain
with some metaprogramming involved...
I haven't tried this out personally yet, but just leaving a note here in case anyone else is intested.
精彩评论