Skip to content

Commit

Permalink
make UserActionObserver work (Rails bug #4087)
Browse files Browse the repository at this point in the history
Monkeypatch ActiveRecord::Observer to always return true after
`notify_observers` in "_notify_observers_for_#{method}" callbacks,
making it again possible to observe before_* events without these
methods halting the callbacks chain all the time.
  • Loading branch information
mislav committed Mar 2, 2010
1 parent 97068b5 commit 6ee313d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
4 changes: 2 additions & 2 deletions app/models/user_action_observer.rb
Expand Up @@ -4,10 +4,10 @@ class UserActionObserver < ActiveRecord::Observer
cattr_accessor :current_user

def before_create(model)
model.created_by = @@current_user
model.created_by = current_user
end

def before_update(model)
model.updated_by = @@current_user
model.updated_by = current_user
end
end
22 changes: 21 additions & 1 deletion config/initializers/active_record_extensions.rb
@@ -1,6 +1,6 @@
require 'active_record'

class ActiveRecord::Base
ActiveRecord::Base.class_eval do
def self.object_id_attr(symbol, klass)
module_eval %{
def #{symbol}
Expand All @@ -16,3 +16,23 @@ def #{symbol}
}
end
end

ActiveRecord::Observer.class_eval do
protected
alias_method :original_add_observer!, :add_observer!

# monkeypatch to fix observers for before_* callbacks
def add_observer!(klass)
super

# Check if a notifier callback was already added to the given class. If
# it was not, add it.
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

0 comments on commit 6ee313d

Please sign in to comment.