Hmm, perhaps you could be more clear? Refactoring in terms of being
able to read the code easily? Or do you mean that when using this
syntax that it would be harder to make changes to it? Additonally, I
think an observer should 'declare' what it is observing, rather than
defining callback methods that happen to be called back by an active
record observer. Also, the blocks of code aren't as anonymous as you
think. They are used to define callback methods that are recognized in
ActiveRecord::Callbacks::CALLBACKS, so debugging the stack trace will
not lead you block invocations, but to the declarations made in the
observer.
Here is why I think refactoring would be easier using the syntax that
is provided in the patch
== Current way of observing
I want to feed a monkey after I create or update one if it is hungry
and was a well behaved monkey
class MonkeyObserver < ActiveRecord::Observer
def after_validation_on_create(monkey)
if monkey.hungry?
ZooKeeper.feed(monkey)
end
end
def after_validation_on_update(monkey)
if monkey.hungry?
ZooKeeper.feed(monkey)
end
end
end
Lets refactor that so that we aren't duplicating code...
class MonkeyObserver < ActiveRecord::Observer
def after_validation_on_create(monkey)
feed_monkey(monkey)
end
def after_validation_on_update(monkey)
feed_monkey(monkey)
end
private
def feed_monkey(monkey)
if monkey.hungry?
ZooKeeper.feed(monkey)
end
end
end
Personally, I don't like that nearly as much as...
== Declarative Observer
class MonkeyObserver < ActiveRecord::Observer
after :validation, :on => :create do |monkey|
if monkey.hungry?
ZooKeeper.feed(monkey)
end
end
after :validation, :on => :update do |monkey|
if monkey.hungry?
ZooKeeper.feed(monkey)
end
end
end
After refactoring....
class MonkeyObserver < ActiveRecord::Observer
after :validation, :on => [:create, :update] do |monkey|
if monkey.hungry?
ZooKeeper.feed(monkey)
end
end
end
I think the intent of the observer is clearer this way, and the
refactoring is much lighter and cleaner IMO.