Simple way of turning off observers during rake task?
Rails 3.1 finally comes with API for this:http://api.rubyonrails.org/v3.1.0/classes/ActiveModel/ObserverArray.html#method-i-disable
ORM.observers.disable :user_observer # => disables the UserObserverUser.observers.disable AuditTrail # => disables the AuditTrail observer for User notifications. # Other models will still notify the AuditTrail observer.ORM.observers.disable :observer_1, :observer_2 # => disables Observer1 and Observer2 for all models.ORM.observers.disable :all # => disables all observers for all models.User.observers.disable :all do # all user observers are disabled for # just the duration of the blockend
Where ORM
could for example be ActiveRecord::Base
You could add an accessor to your user model, something like "skip_activation" that wouldn't need to be saved, but would persist through the session, and then check the flag in the observer. Something like
class User attr_accessor :skip_activation #whateverend
Then, in the observer:
def after_save(user) return if user.skip_activation #rest of stuff to send emailend
As a flag for the observer I like to define a class accessor called "disabled" so it reads like this:
class ActivityObserver < ActiveRecord::Observer observe :user # used in tests to disable the observer on demand. cattr_accessor(:disabled)end
I put it as a condition in the sensitive callbacks
def after_create(record) return if ActivityObserver.disabled # do_somethingend
and I just turn the flag on when needed
ActivityObserver.disabled=true