| Module | ActiveModel::Observing::ClassMethods |
| In: |
lib/rails/observers/active_model/observing.rb
|
Add a new observer to the pool. The new observer needs to respond to update, otherwise it raises an ArgumentError exception.
class Foo
include ActiveModel::Observing
end
class FooObserver < ActiveModel::Observer
end
Foo.add_observer(FooObserver.instance)
Foo.observers_instance
# => [#<FooObserver:0x007fccf55d9390>]
Instantiate the global observers.
class Foo
include ActiveModel::Observing
attr_accessor :status
end
class FooObserver < ActiveModel::Observer
def on_spec(record, *args)
record.status = true
end
end
Foo.observers = FooObserver
foo = Foo.new
foo.status = false
foo.notify_observers(:on_spec)
foo.status # => false
Foo.instantiate_observers # => [FooObserver]
foo = Foo.new
foo.status = false
foo.notify_observers(:on_spec)
foo.status # => true
Fires notifications to model‘s observers.
def save
notify_observers(:before_save)
...
notify_observers(:after_save)
end
Custom notifications can be sent in a similar fashion:
notify_observers(:custom_notification, :foo)
This will call custom_notification, passing as arguments the current object and :foo.
Returns the current observer instances.
class Foo
include ActiveModel::Observing
attr_accessor :status
end
class FooObserver < ActiveModel::Observer
def on_spec(record, *args)
record.status = true
end
end
Foo.observers = FooObserver
Foo.instantiate_observers
Foo.observer_instances # => [#<FooObserver:0x007fc212c40820>]
Gets an array of observers observing this model. The array also provides enable and disable methods that allow you to selectively enable and disable observers (see ActiveModel::ObserverArray.enable and ActiveModel::ObserverArray.disable for more on this).
class ORM
include ActiveModel::Observing
end
ORM.observers = :cacher, :garbage_collector
ORM.observers # => [:cacher, :garbage_collector]
ORM.observers.class # => ActiveModel::ObserverArray
Activates the observers assigned.
class ORM
include ActiveModel::Observing
end
# Calls PersonObserver.instance
ORM.observers = :person_observer
# Calls Cacher.instance and GarbageCollector.instance
ORM.observers = :cacher, :garbage_collector
# Same as above, just using explicit class references
ORM.observers = Cacher, GarbageCollector
Note: Setting this does not instantiate the observers yet. instantiate_observers is called during startup, and before each development request.
Returns the total number of instantiated observers.
class Foo
include ActiveModel::Observing
attr_accessor :status
end
class FooObserver < ActiveModel::Observer
def on_spec(record, *args)
record.status = true
end
end
Foo.observers = FooObserver
Foo.observers_count # => 0
Foo.instantiate_observers
Foo.observers_count # => 1