Created
January 10, 2011 19:56
-
-
Save outoftime/773343 to your computer and use it in GitHub Desktop.
Use ActiveModel observers with your Mongoid 2 models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mongoid | |
module Observing | |
CALLBACKS = [ | |
:before_create, :before_destroy, :before_save, :before_update, | |
:before_validation, :after_create, :after_destroy, :after_save, | |
:after_update, :after_validation | |
] | |
def self.included(base) | |
base.module_eval { include ActiveModel::Observing } | |
CALLBACKS.each do |callback| | |
callback_method = :"notify_observers_#{callback}" | |
base.module_eval <<-RUBY, __FILE__, __LINE__+1 | |
#{callback}(#{callback_method.inspect}) | |
def #{callback_method}(&block) | |
notify_observers(#{callback.inspect}, &block) | |
end | |
private #{callback_method.inspect} | |
RUBY | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
registering ActiveModel observers with ActiveRecord::Base.observers= doesn't work when cache classes is turned on, whereisciao's solution works great, thx!