diff options
author | David Heinemeier Hansson <david@loudthinking.com> | 2005-09-25 08:26:29 +0000 |
---|---|---|
committer | David Heinemeier Hansson <david@loudthinking.com> | 2005-09-25 08:26:29 +0000 |
commit | 948be2c998c9e3e56da742b38bc0ab57b75c8d2d (patch) | |
tree | 9b078f37ccefd4c0943c1c0080c5a1a572118d4d /activerecord/lib/active_record | |
parent | 2346f5716f7b08168b74b29e0279d51c51557b08 (diff) | |
download | rails-948be2c998c9e3e56da742b38bc0ab57b75c8d2d.tar.gz rails-948be2c998c9e3e56da742b38bc0ab57b75c8d2d.tar.bz2 rails-948be2c998c9e3e56da742b38bc0ab57b75c8d2d.zip |
Added new symbol-driven approach to activating observers with Base#observer [DHH]
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@2326 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r-- | activerecord/lib/active_record/observer.rb | 33 |
1 files changed, 32 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/observer.rb b/activerecord/lib/active_record/observer.rb index 36a9ec5d3a..36fcf021cd 100644 --- a/activerecord/lib/active_record/observer.rb +++ b/activerecord/lib/active_record/observer.rb @@ -1,6 +1,36 @@ require 'singleton' module ActiveRecord + module Observing # :nodoc: + def self.append_features(base) + super + base.extend(ClassMethods) + end + + module ClassMethods + # Activates the observers assigned. Examples: + # + # # Calls PersonObserver.instance and returns the instance of that observer + # ActiveRecord::Base.observer(:person_observer) + # + # # Calls Cacher.instance and GarbageCollector.instance + # # and returns an array with instances of both + # ActiveRecord::Base.observer(:cacher, :garbage_collector) + # + # # Same as above, just using explicit class references + # ActiveRecord::Base.observer(Cacher, GarbageCollector) + def observer(*observers) + observers = [ observers ].flatten.collect do |observer| + observer.is_a?(Symbol) ? + observer.to_s.camelize.constantize.instance : + observer.instance + end + + observers.size > 1 ? observers : observers.first + end + end + end + # Observer classes respond to lifecycle callbacks to implement trigger-like # behavior outside the original class. This is a great way to reduce the # clutter that normally comes when the model class is burdened with @@ -48,7 +78,8 @@ module ActiveRecord # == Triggering Observers # # In order to activate an observer, you need to call Observer.instance. In Rails, this can be done in controllers - # using the short-hand of for example observer :comment_observer. + # using the short-hand of for example observer :comment_observer. Or directly from Active Record, with + # ActiveRecord::Base.observer(:comment_observer). class Observer include Singleton |