Skip to content

Instantly share code, notes, and snippets.

@outoftime
Created January 10, 2011 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save outoftime/773343 to your computer and use it in GitHub Desktop.
Save outoftime/773343 to your computer and use it in GitHub Desktop.
Use ActiveModel observers with your Mongoid 2 models
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
@whereisciao
Copy link

Hey Mat, How are you registering your Observers? This by far is the best source I have for setting up mongoid observers.

@outoftime
Copy link
Author

I'm actually just passing them into ActiveRecord::Base.observers= in an initializer -- not particularly accurate semantically, but it has the intended effect.

@whereisciao
Copy link

Thanks for the info. Its seems there is no way to get rid of ActiveRecord--my app has AR cut out at the moment.

@outoftime
Copy link
Author

Ohh, good call -- I use the two in conjunction. I'd dig around in the AR internals to see what it does when it instantiates observers -- I'll bet it's something simple that you can replicate in an initializer etc...

@whereisciao
Copy link

A message in the Google Group simply initialized the observers in the observed model. Here is my fork based on it with an initializer. What I am trying to achieve next is adding a new Mongoid Config option.

@whatwho
Copy link

whatwho commented May 24, 2012

registering ActiveModel observers with ActiveRecord::Base.observers= doesn't work when cache classes is turned on, whereisciao's solution works great, thx!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment