5 module Observing
# :nodoc:
6 def self.included(base
)
7 base
.extend ClassMethods
11 # Activates the observers assigned. Examples:
13 # # Calls PersonObserver.instance
14 # ActiveRecord::Base.observers = :person_observer
16 # # Calls Cacher.instance and GarbageCollector.instance
17 # ActiveRecord::Base.observers = :cacher, :garbage_collector
19 # # Same as above, just using explicit class references
20 # ActiveRecord::Base.observers = Cacher, GarbageCollector
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
28 # Gets the current observers.
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)
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"
48 # Notify observers when the observed class is subclassed.
49 def inherited(subclass
)
52 notify_observers
:observed_class_inherited, subclass
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
63 # class CommentObserver < ActiveRecord::Observer
64 # def after_save(comment)
65 # Notifications.deliver_comment("admin@do.com", "New comment was posted", comment)
69 # This Observer sends an email when a Comment#save is finished.
71 # class ContactObserver < ActiveRecord::Observer
72 # def after_create(contact)
73 # contact.logger.info('New contact added!')
76 # def after_destroy(contact)
77 # contact.logger.warn("Contact with an id of #{contact.id} was destroyed!")
81 # This Observer uses logger to log when specific callbacks are triggered.
83 # == Observing a class that can't be inferred
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):
90 # class AuditObserver < ActiveRecord::Observer
93 # def after_update(account)
94 # AuditTrail.new(account, "UPDATED")
98 # If the audit observer needs to watch more than one kind of object, this can be specified with multiple arguments:
100 # class AuditObserver < ActiveRecord::Observer
101 # observe :account, :balance
103 # def after_update(record)
104 # AuditTrail.new(record, "UPDATED")
108 # The AuditObserver will now act on both updates to Account and Balance by treating them both as records.
110 # == Available callback methods
112 # The observer can implement callback methods for each of the methods described in the Callbacks module.
114 # == Storing Observers in Rails
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.
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.
124 # config.active_record.observers = :comment_observer, :signup_observer
126 # Observers will not be invoked unless you define these in your application configuration.
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.
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.
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.
146 # Attaches the observer to the supplied model classes.
149 models
.collect
! { |model
| model
.is_a
?(Symbol
) ? model
.to_s
.camelize
.constantize
: model
}
150 define_method(:observed_classes) { Set
.new(models
) }
153 # The class observed by default is inferred from the observer's class name:
154 # assert_equal Person, PersonObserver.observed_class
156 if observed_class_name
= name
[/(.*)Observer/, 1]
157 observed_class_name
.constantize
164 # Start observing the declared classes and their subclasses.
166 Set
.new(observed_classes
+ observed_subclasses
).each
{ |klass
| add_observer
! klass
}
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
)
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
)
183 Set
.new([self.class.observed_class
].compact
.flatten
)
186 def observed_subclasses
187 observed_classes
.sum([]) { |klass
| klass
.send(:subclasses) }
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'