Skip to content

Instantly share code, notes, and snippets.

@whereisciao
Forked from outoftime/observing.rb
Created February 10, 2011 15:34

Revisions

  1. whereisciao revised this gist Feb 10, 2011. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions mongoid.rb
    Original file line number Diff line number Diff line change
    @@ -4,3 +4,8 @@

    User.observers = :user_observer
    User.instantiate_observers

    # The preferred syntax, similar to AR's setup
    # Mongoid.configure do |config|
    # config.observers = :user_observer
    # end
  2. whereisciao revised this gist Feb 10, 2011. 4 changed files with 21 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions mongoid.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    require "#{RAILS_ROOT}/lib/mongoid/lib/observing.rb"

    # Initializer for Observers

    User.observers = :user_observer
    User.instantiate_observers
    File renamed without changes.
    10 changes: 10 additions & 0 deletions user.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    require 'carrierwave/orm/mongoid'

    class User
    include Mongoid::Document
    include Mongoid::Timestamps
    include Mongoid::Observing

    field :name
    field :username
    end
    5 changes: 5 additions & 0 deletions user_observer.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    class UserObserver < ActiveModel::Observer
    def after_validation(user)
    puts "User Observer After Validation"
    end
    end
  3. @outoftime outoftime created this gist Jan 10, 2011.
    26 changes: 26 additions & 0 deletions mongoid/observing.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    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