module ActiveModel::Observing::ClassMethods
def add_observer(observer)
def add_observer(observer) unless observer.respond_to? :update raise ArgumentError, "observer needs to respond to `update'" end @observer_instances ||= [] @observer_instances << observer end
def count_observers
def count_observers @observer_instances.size end
def inherited(subclass)
def inherited(subclass) super notify_observers :observed_class_inherited, subclass end
def instantiate_observer(observer) #:nodoc:
def instantiate_observer(observer) #:nodoc: # 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
def instantiate_observers
def instantiate_observers observers.each { |o| instantiate_observer(o) } end
def notify_observers(*arg)
def notify_observers(*arg) if defined? @observer_instances for observer in @observer_instances observer.update(*arg) end end end
def observers
def observers @observers ||= [] end
def observers=(*values)
+instantiate_observers+ is called during startup, and before
Note: Setting this does not instantiate the observers yet.
ActiveRecord::Base.observers = Cacher, GarbageCollector
# Same as above, just using explicit class references
ActiveRecord::Base.observers = :cacher, :garbage_collector
# Calls Cacher.instance and GarbageCollector.instance
ActiveRecord::Base.observers = :person_observer
# Calls PersonObserver.instance
Activates the observers assigned. Examples:
== Active Model Observers Activation
def observers=(*values) @observers = values.flatten end