observing.rb 8.0 KB
Newer Older
R
rick 已提交
1
require 'singleton'
2
require 'active_model/observer_array'
3
require 'active_support/core_ext/module/aliasing'
4
require 'active_support/core_ext/module/remove_method'
5
require 'active_support/core_ext/string/inflections'
6
require 'active_support/core_ext/enumerable'
7
require 'active_support/descendants_tracker'
8 9 10

module ActiveModel
  module Observing
11 12
    extend ActiveSupport::Concern

13 14 15 16
    included do
      extend ActiveSupport::DescendantsTracker
    end

17
    module ClassMethods
R
Rizwan Reza 已提交
18
      # == Active Model Observers Activation
19
      #
20 21
      # Activates the observers assigned. Examples:
      #
22 23 24 25
      #   class ORM
      #     include ActiveModel::Observing
      #   end
      #
26
      #   # Calls PersonObserver.instance
27
      #   ORM.observers = :person_observer
28 29
      #
      #   # Calls Cacher.instance and GarbageCollector.instance
30
      #   ORM.observers = :cacher, :garbage_collector
31 32
      #
      #   # Same as above, just using explicit class references
33
      #   ORM.observers = Cacher, GarbageCollector
34
      #
35
      # Note: Setting this does not instantiate the observers yet.
36 37
      # +instantiate_observers+ is called during startup, and before
      # each development request.
38
      def observers=(*values)
39
        observers.replace(values.flatten)
40
      end
41

42 43 44 45 46
      # Gets an array of observers observing this model.
      # The array also provides +enable+ and +disable+ methods
      # that allow you to selectively enable and disable observers.
      # (see <tt>ActiveModel::ObserverArray.enable</tt> and
      # <tt>ActiveModel::ObserverArray.disable</tt> for more on this)
47
      def observers
48
        @observers ||= ObserverArray.new(self)
49 50
      end

51 52 53 54 55
      # Gets the current observer instances.
      def observer_instances
        @observer_instances ||= []
      end

56
      # Instantiate the global observers.
57 58 59
      def instantiate_observers
        observers.each { |o| instantiate_observer(o) }
      end
60

X
Xavier Noria 已提交
61
      # Add a new observer to the pool.
62 63
      # The new observer needs to respond to 'update', otherwise it
      # raises an +ArgumentError+ exception.
64 65
      def add_observer(observer)
        unless observer.respond_to? :update
66
          raise ArgumentError, "observer needs to respond to 'update'"
67
        end
68
        observer_instances << observer
69 70
      end

X
Xavier Noria 已提交
71
      # Notify list of observers of a change.
72 73
      def notify_observers(*args)
        observer_instances.each { |observer| observer.update(*args) }
74 75
      end

X
Xavier Noria 已提交
76
      # Total number of observers.
J
Jeremy Kemper 已提交
77
      def count_observers
78
        observer_instances.size
J
Jeremy Kemper 已提交
79 80
      end

81
      protected
J
Joshua Peek 已提交
82
        def instantiate_observer(observer) #:nodoc:
83 84
          # string/symbol
          if observer.respond_to?(:to_sym)
P
Paco Guzman 已提交
85
            observer.to_s.camelize.constantize.instance
86 87 88
          elsif observer.respond_to?(:instance)
            observer.instance
          else
89 90 91 92 93
            raise ArgumentError,
              "#{observer} must be a lowercase, underscored class name (or an " +
              "instance of the class itself) responding to the instance " +
              "method. Example: Person.observers = :big_brother # calls " +
              "BigBrother.instance"
94 95 96 97 98 99 100
          end
        end

        # Notify observers when the observed class is subclassed.
        def inherited(subclass)
          super
          notify_observers :observed_class_inherited, subclass
101 102
        end
    end
103 104

    private
J
Joshua Peek 已提交
105 106 107 108 109 110 111
      # Fires notifications to model's observers
      #
      # def save
      #   notify_observers(:before_save)
      #   ...
      #   notify_observers(:after_save)
      # end
112
      def notify_observers(method)
113 114
        self.class.notify_observers(method, self)
      end
115 116
  end

R
Rizwan Reza 已提交
117 118
  # == Active Model Observers
  #
119
  # Observer classes respond to life cycle callbacks to implement trigger-like
J
Joshua Peek 已提交
120 121 122 123 124 125 126
  # behavior outside the original class. This is a great way to reduce the
  # clutter that normally comes when the model class is burdened with
  # functionality that doesn't pertain to the core responsibility of the
  # class. Example:
  #
  #   class CommentObserver < ActiveModel::Observer
  #     def after_save(comment)
127
  #       Notifications.comment("admin@do.com", "New comment was posted", comment).deliver
J
Joshua Peek 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  #     end
  #   end
  #
  # This Observer sends an email when a Comment#save is finished.
  #
  #   class ContactObserver < ActiveModel::Observer
  #     def after_create(contact)
  #       contact.logger.info('New contact added!')
  #     end
  #
  #     def after_destroy(contact)
  #       contact.logger.warn("Contact with an id of #{contact.id} was destroyed!")
  #     end
  #   end
  #
  # This Observer uses logger to log when specific callbacks are triggered.
  #
  # == Observing a class that can't be inferred
  #
147 148
  # Observers will by default be mapped to the class with which they share a
  # name. So CommentObserver will be tied to observing Comment, ProductManagerObserver
149
  # to ProductManager, and so on. If you want to name your observer differently than
150 151
  # the class you're interested in observing, you can use the <tt>Observer.observe</tt>
  # class method which takes either the concrete class (Product) or a symbol for that
152
  # class (:product):
J
Joshua Peek 已提交
153 154 155 156 157 158 159 160 161
  #
  #   class AuditObserver < ActiveModel::Observer
  #     observe :account
  #
  #     def after_update(account)
  #       AuditTrail.new(account, "UPDATED")
  #     end
  #   end
  #
162
  # If the audit observer needs to watch more than one kind of object, this can be
163
  # specified with multiple arguments:
J
Joshua Peek 已提交
164 165 166 167 168 169 170 171 172
  #
  #   class AuditObserver < ActiveModel::Observer
  #     observe :account, :balance
  #
  #     def after_update(record)
  #       AuditTrail.new(record, "UPDATED")
  #     end
  #   end
  #
173
  # The AuditObserver will now act on both updates to Account and Balance by treating
174
  # them both as records.
J
Joshua Peek 已提交
175
  #
176 177 178 179
  # If you're using an Observer in a Rails application with Active Record, be sure to
  # read about the necessary configuration in the documentation for
  # ActiveRecord::Observer.
  #
180 181
  class Observer
    include Singleton
182
    extend ActiveSupport::DescendantsTracker
183 184 185 186

    class << self
      # Attaches the observer to the supplied model classes.
      def observe(*models)
187 188
        models.flatten!
        models.collect! { |model| model.respond_to?(:to_sym) ? model.to_s.camelize.constantize : model }
189
        redefine_method(:observed_classes) { models }
190 191
      end

J
Joshua Peek 已提交
192 193 194 195 196 197
      # Returns an array of Classes to observe.
      #
      # You can override this instead of using the +observe+ helper.
      #
      #   class AuditObserver < ActiveModel::Observer
      #     def self.observed_classes
198
      #       [Account, Balance]
J
Joshua Peek 已提交
199 200
      #     end
      #   end
201
      def observed_classes
202
        Array(observed_class)
203 204 205
      end

      # The class observed by default is inferred from the observer's class name:
206
      #   assert_equal Person, PersonObserver.observed_class
207
      def observed_class
208
        if observed_class_name = name[/(.*)Observer/, 1]
209 210 211 212 213 214 215 216
          observed_class_name.constantize
        else
          nil
        end
      end
    end

    # Start observing the declared classes and their subclasses.
O
Oscar Del Ben 已提交
217
    # Called automatically by the instance method.
218
    def initialize
219 220 221
      observed_classes.each { |klass| add_observer!(klass) }
    end

J
Joshua Peek 已提交
222
    def observed_classes #:nodoc:
223
      self.class.observed_classes
224 225
    end

226 227
    # Send observed_method(object) if the method exists and
    # the observer is enabled for the given object's class.
228
    def update(observed_method, object, &block) #:nodoc:
229 230
      return unless respond_to?(observed_method)
      return if disabled_for?(object)
231
      send(observed_method, object, &block)
232 233 234 235 236 237
    end

    # Special method sent by the observed class when it is inherited.
    # Passes the new subclass.
    def observed_class_inherited(subclass) #:nodoc:
      self.class.observe(observed_classes + [subclass])
238
      add_observer!(subclass)
239 240
    end

241
    protected
J
Joshua Peek 已提交
242
      def add_observer!(klass) #:nodoc:
243 244
        klass.add_observer(self)
      end
245

O
Oscar Del Ben 已提交
246
      # Returns true if notifications are disabled for this object.
247 248 249 250 251
      def disabled_for?(object)
        klass = object.class
        return false unless klass.respond_to?(:observers)
        klass.observers.disabled_for?(self)
      end
252
  end
253
end