~michaelforrest/use-case-mapper/trunk

« back to all changes in this revision

Viewing changes to vendor/rails/activerecord/lib/active_record/observer.rb

  • Committer: Michael Forrest
  • Date: 2010-10-15 16:28:50 UTC
  • Revision ID: michael.forrest@canonical.com-20101015162850-tj2vchanv0kr0dun
refrozeĀ gems

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
require 'singleton'
 
2
require 'set'
 
3
 
 
4
module ActiveRecord
 
5
  module Observing # :nodoc:
 
6
    def self.included(base)
 
7
      base.extend ClassMethods
 
8
    end
 
9
 
 
10
    module ClassMethods
 
11
      # Activates the observers assigned. Examples:
 
12
      #
 
13
      #   # Calls PersonObserver.instance
 
14
      #   ActiveRecord::Base.observers = :person_observer
 
15
      #
 
16
      #   # Calls Cacher.instance and GarbageCollector.instance
 
17
      #   ActiveRecord::Base.observers = :cacher, :garbage_collector
 
18
      #
 
19
      #   # Same as above, just using explicit class references
 
20
      #   ActiveRecord::Base.observers = Cacher, GarbageCollector
 
21
      #
 
22
      # Note: Setting this does not instantiate the observers yet. +instantiate_observers+ is
 
23
      # called during startup, and before each development request.
 
24
      def observers=(*observers)
 
25
        @observers = observers.flatten
 
26
      end
 
27
 
 
28
      # Gets the current observers.
 
29
      def observers
 
30
        @observers ||= []
 
31
      end
 
32
 
 
33
      # Instantiate the global Active Record observers.
 
34
      def instantiate_observers
 
35
        return if @observers.blank?
 
36
        @observers.each do |observer|
 
37
          if observer.respond_to?(:to_sym) # Symbol or String
 
38
            observer.to_s.camelize.constantize.instance
 
39
          elsif observer.respond_to?(:instance)
 
40
            observer.instance
 
41
          else
 
42
            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"
 
43
          end
 
44
        end
 
45
      end
 
46
 
 
47
      protected
 
48
        # Notify observers when the observed class is subclassed.
 
49
        def inherited(subclass)
 
50
          super
 
51
          changed
 
52
          notify_observers :observed_class_inherited, subclass
 
53
        end
 
54
    end
 
55
  end
 
56
 
 
57
  # Observer classes respond to lifecycle callbacks to implement trigger-like
 
58
  # behavior outside the original class. This is a great way to reduce the
 
59
  # clutter that normally comes when the model class is burdened with
 
60
  # functionality that doesn't pertain to the core responsibility of the
 
61
  # class. Example:
 
62
  #
 
63
  #   class CommentObserver < ActiveRecord::Observer
 
64
  #     def after_save(comment)
 
65
  #       Notifications.deliver_comment("admin@do.com", "New comment was posted", comment)
 
66
  #     end
 
67
  #   end
 
68
  #
 
69
  # This Observer sends an email when a Comment#save is finished.
 
70
  #
 
71
  #   class ContactObserver < ActiveRecord::Observer
 
72
  #     def after_create(contact)
 
73
  #       contact.logger.info('New contact added!')
 
74
  #     end
 
75
  #
 
76
  #     def after_destroy(contact)
 
77
  #       contact.logger.warn("Contact with an id of #{contact.id} was destroyed!")
 
78
  #     end
 
79
  #   end
 
80
  #
 
81
  # This Observer uses logger to log when specific callbacks are triggered.
 
82
  #
 
83
  # == Observing a class that can't be inferred
 
84
  #
 
85
  # Observers will by default be mapped to the class with which they share a name. So CommentObserver will
 
86
  # be tied to observing Comment, ProductManagerObserver to ProductManager, and so on. If you want to name your observer
 
87
  # differently than the class you're interested in observing, you can use the Observer.observe class method which takes
 
88
  # either the concrete class (Product) or a symbol for that class (:product):
 
89
  #
 
90
  #   class AuditObserver < ActiveRecord::Observer
 
91
  #     observe :account
 
92
  #
 
93
  #     def after_update(account)
 
94
  #       AuditTrail.new(account, "UPDATED")
 
95
  #     end
 
96
  #   end
 
97
  #
 
98
  # If the audit observer needs to watch more than one kind of object, this can be specified with multiple arguments:
 
99
  #
 
100
  #   class AuditObserver < ActiveRecord::Observer
 
101
  #     observe :account, :balance
 
102
  #
 
103
  #     def after_update(record)
 
104
  #       AuditTrail.new(record, "UPDATED")
 
105
  #     end
 
106
  #   end
 
107
  #
 
108
  # The AuditObserver will now act on both updates to Account and Balance by treating them both as records.
 
109
  #
 
110
  # == Available callback methods
 
111
  #
 
112
  # The observer can implement callback methods for each of the methods described in the Callbacks module.
 
113
  #
 
114
  # == Storing Observers in Rails
 
115
  #
 
116
  # If you're using Active Record within Rails, observer classes are usually stored in app/models with the
 
117
  # naming convention of app/models/audit_observer.rb.
 
118
  #
 
119
  # == Configuration
 
120
  #
 
121
  # In order to activate an observer, list it in the <tt>config.active_record.observers</tt> configuration setting in your
 
122
  # <tt>config/environment.rb</tt> file.
 
123
  #
 
124
  #   config.active_record.observers = :comment_observer, :signup_observer
 
125
  #
 
126
  # Observers will not be invoked unless you define these in your application configuration.
 
127
  #
 
128
  # == Loading
 
129
  #
 
130
  # Observers register themselves in the model class they observe, since it is the class that
 
131
  # notifies them of events when they occur. As a side-effect, when an observer is loaded its
 
132
  # corresponding model class is loaded.
 
133
  #
 
134
  # Up to (and including) Rails 2.0.2 observers were instantiated between plugins and
 
135
  # application initializers. Now observers are loaded after application initializers,
 
136
  # so observed models can make use of extensions.
 
137
  #
 
138
  # If by any chance you are using observed models in the initialization you can still
 
139
  # load their observers by calling <tt>ModelObserver.instance</tt> before. Observers are
 
140
  # singletons and that call instantiates and registers them.
 
141
  #
 
142
  class Observer
 
143
    include Singleton
 
144
 
 
145
    class << self
 
146
      # Attaches the observer to the supplied model classes.
 
147
      def observe(*models)
 
148
        models.flatten!
 
149
        models.collect! { |model| model.is_a?(Symbol) ? model.to_s.camelize.constantize : model }
 
150
        define_method(:observed_classes) { Set.new(models) }
 
151
      end
 
152
 
 
153
      # The class observed by default is inferred from the observer's class name:
 
154
      #   assert_equal Person, PersonObserver.observed_class
 
155
      def observed_class
 
156
        if observed_class_name = name[/(.*)Observer/, 1]
 
157
          observed_class_name.constantize
 
158
        else
 
159
          nil
 
160
        end
 
161
      end
 
162
    end
 
163
 
 
164
    # Start observing the declared classes and their subclasses.
 
165
    def initialize
 
166
      Set.new(observed_classes + observed_subclasses).each { |klass| add_observer! klass }
 
167
    end
 
168
 
 
169
    # Send observed_method(object) if the method exists.
 
170
    def update(observed_method, object) #:nodoc:
 
171
      send(observed_method, object) if respond_to?(observed_method)
 
172
    end
 
173
 
 
174
    # Special method sent by the observed class when it is inherited.
 
175
    # Passes the new subclass.
 
176
    def observed_class_inherited(subclass) #:nodoc:
 
177
      self.class.observe(observed_classes + [subclass])
 
178
      add_observer!(subclass)
 
179
    end
 
180
 
 
181
    protected
 
182
      def observed_classes
 
183
        Set.new([self.class.observed_class].compact.flatten)
 
184
      end
 
185
 
 
186
      def observed_subclasses
 
187
        observed_classes.sum([]) { |klass| klass.send(:subclasses) }
 
188
      end
 
189
 
 
190
      def add_observer!(klass)
 
191
        klass.add_observer(self)
 
192
        if respond_to?(:after_find) && !klass.method_defined?(:after_find)
 
193
          klass.class_eval 'def after_find() end'
 
194
        end
 
195
      end
 
196
  end
 
197
end