Skip to content

Instantly share code, notes, and snippets.

@gawin
Forked from whereisciao/mongoid.rb
Created May 24, 2011 14:24
Show Gist options
  • Save gawin/988791 to your computer and use it in GitHub Desktop.
Save gawin/988791 to your computer and use it in GitHub Desktop.
Mongoid Observer using ActiveModel.
require "#{RAILS_ROOT}/lib/mongoid/lib/observing.rb"
# Initializer for Observers
User.observers = :user_observer
User.instantiate_observers
# The preferred syntax, similar to AR's setup
# Mongoid.configure do |config|
# config.observers = :user_observer
# end
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
def #{callback_method}(&block)
notify_observers(#{callback.inspect}, &block)
end
private #{callback_method.inspect}
RUBY
end
end
end
end
require 'carrierwave/orm/mongoid'
class User
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Observing
field :name
field :username
end
class UserObserver < ActiveModel::Observer
def after_validation(user)
puts "User Observer After Validation"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment