This project is archived and is in readonly mode.
ActiveRecord observers can't be used for "before" callbacks
-
Mislav
- Tag changed from activerecord, callbacks, observers to activerecord, callbacks, observers, rails3
-
Sven Fuchs
Gosh, I ran into the same thing today.
As long as you don't care about the return value this hax seems to work for now
ActiveRecord::Observer.class_eval do def add_observer!(klass) super self.class.observed_methods.each do |method| callback = :"_notify_observers_for_#{method}" if (klass.instance_methods & [callback, callback.to_s]).empty? klass.class_eval "def #{callback}; notify_observers(:#{method}); true; end" klass.send(method, callback) end end end end -
Mislav
That's the exact monkeypatch I did in Radiant
-
Yehuda Katz (wycats)
- Assigned user set to Yehuda Katz (wycats)
-
Mislav
- Tag changed from activerecord, callbacks, observers, rails3 to activerecord, callbacks, observers, rails3, regression
Failing test
-
Mislav
Taken a stab at fixing this. This patch includes changes from the above patch. Detailed explanation of the changes in commit messages, but here is the last (and most important):
improve how ActiveRecord::Observer defines callbacks on observed models
Instead of using a single
notify_observerscall for every callback type, each observer now registers a unique callback for itself. Example:before_save :_notify_user_observer_for_before_save def _notify_user_observer_for_before_save observer.update(:before_save, self) endBenefit: "before" callbacks halt when
observer.updatereturns false. This way, ActiveRecord observers can prevent records from saving. -
Repository
- State changed from new to committed
(from [2161b8745a22379356b466a60b9aa763c0593f9b]) improve how ActiveRecord::Observer defines callbacks on observed models
Instead of using a single
notify_observerscall for every callback type,
each observer now registers a unique callback for itself. Example:before_save :_notify_user_observer_for_before_save
def _notify_user_observer_for_before_save
observer.update(:before_save, self)end
Benefit: "before" callbacks halt when
observer.updatereturns false.
This way, ActiveRecord observers can prevent records from saving.[#4087 ActiveRecord observers can't be used for "before" callbacks state:committed]
Signed-off-by: Jeremy Kemper jeremy@bitsweat.net
http://github.com/rails/rails/commit/2161b8745a22379356b466a60b9aa7...
