observing.rb 6.7 KB
Newer Older
R
rick 已提交
1
require 'singleton'
J
Joshua Peek 已提交
2
require 'active_support/core_ext/array/wrap'
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 7 8

module ActiveModel
  module Observing
9 10
    extend ActiveSupport::Concern

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

      # Gets the current observers.
      def observers
        @observers ||= []
      end

41 42 43 44 45
      # Gets the current observer instances.
      def observer_instances
        @observer_instances ||= []
      end

46
      # Instantiate the global Active Record observers.
47 48 49
      def instantiate_observers
        observers.each { |o| instantiate_observer(o) }
      end
50

51 52 53 54
      def add_observer(observer)
        unless observer.respond_to? :update
          raise ArgumentError, "observer needs to respond to `update'"
        end
55
        observer_instances << observer
56 57 58
      end

      def notify_observers(*arg)
59 60
        for observer in observer_instances
          observer.update(*arg)
61 62 63
        end
      end

J
Jeremy Kemper 已提交
64
      def count_observers
65
        observer_instances.size
J
Jeremy Kemper 已提交
66 67
      end

68
      protected
J
Joshua Peek 已提交
69
        def instantiate_observer(observer) #:nodoc:
70 71 72 73 74 75 76 77 78 79 80 81 82 83
          # string/symbol
          if observer.respond_to?(:to_sym)
            observer = observer.to_s.camelize.constantize.instance
          elsif observer.respond_to?(:instance)
            observer.instance
          else
            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"
          end
        end

        # Notify observers when the observed class is subclassed.
        def inherited(subclass)
          super
          notify_observers :observed_class_inherited, subclass
84 85
        end
    end
86 87

    private
J
Joshua Peek 已提交
88 89 90 91 92 93 94
      # Fires notifications to model's observers
      #
      # def save
      #   notify_observers(:before_save)
      #   ...
      #   notify_observers(:after_save)
      # end
95
      def notify_observers(method)
96 97
        self.class.notify_observers(method, self)
      end
98 99
  end

R
Rizwan Reza 已提交
100 101
  # == Active Model Observers
  #
102
  # Observer classes respond to life cycle callbacks to implement trigger-like
J
Joshua Peek 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
  # 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)
  #       Notifications.deliver_comment("admin@do.com", "New comment was posted", comment)
  #     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
  #
130 131
  # Observers will by default be mapped to the class with which they share a
  # name. So CommentObserver will be tied to observing Comment, ProductManagerObserver
132 133 134
  # to ProductManager, and so on. If you want to name your observer differently than
  # the class you're interested in observing, you can use the Observer.observe class
  # method which takes either the concrete class (Product) or a symbol for that
135
  # class (:product):
J
Joshua Peek 已提交
136 137 138 139 140 141 142 143 144
  #
  #   class AuditObserver < ActiveModel::Observer
  #     observe :account
  #
  #     def after_update(account)
  #       AuditTrail.new(account, "UPDATED")
  #     end
  #   end
  #
145
  # If the audit observer needs to watch more than one kind of object, this can be
146
  # specified with multiple arguments:
J
Joshua Peek 已提交
147 148 149 150 151 152 153 154 155
  #
  #   class AuditObserver < ActiveModel::Observer
  #     observe :account, :balance
  #
  #     def after_update(record)
  #       AuditTrail.new(record, "UPDATED")
  #     end
  #   end
  #
156
  # The AuditObserver will now act on both updates to Account and Balance by treating
157
  # them both as records.
J
Joshua Peek 已提交
158
  #
159 160 161 162 163 164
  class Observer
    include Singleton

    class << self
      # Attaches the observer to the supplied model classes.
      def observe(*models)
165 166
        models.flatten!
        models.collect! { |model| model.respond_to?(:to_sym) ? model.to_s.camelize.constantize : model }
167
        remove_possible_method(:observed_classes)
168
        define_method(:observed_classes) { models }
169 170
      end

J
Joshua Peek 已提交
171 172 173 174 175 176
      # 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
177
      #       [Account, Balance]
J
Joshua Peek 已提交
178 179
      #     end
      #   end
180 181
      def observed_classes
        Array.wrap(observed_class)
182 183 184
      end

      # The class observed by default is inferred from the observer's class name:
185
      #   assert_equal Person, PersonObserver.observed_class
186
      def observed_class
187
        if observed_class_name = name[/(.*)Observer/, 1]
188 189 190 191 192 193 194 195 196
          observed_class_name.constantize
        else
          nil
        end
      end
    end

    # Start observing the declared classes and their subclasses.
    def initialize
197 198 199
      observed_classes.each { |klass| add_observer!(klass) }
    end

J
Joshua Peek 已提交
200
    def observed_classes #:nodoc:
201
      self.class.observed_classes
202 203 204 205 206 207 208 209 210 211 212
    end

    # Send observed_method(object) if the method exists.
    def update(observed_method, object) #:nodoc:
      send(observed_method, object) if respond_to?(observed_method)
    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])
213
      add_observer!(subclass)
214 215
    end

216
    protected
J
Joshua Peek 已提交
217
      def add_observer!(klass) #:nodoc:
218 219
        klass.add_observer(self)
      end
220
  end
221
end