Simple way of turning off observers during rake ta

2019-01-13 12:53发布

I'm using restful_authentication in my app. I'm creating a set of default users using a rake task, but every time I run the task an activation email is sent out because of the observer associated with my user model. I'm setting the activation fields when I create the users, so no activation is necessary.

Anyone know of an easy way to bypass observers while running a rake task so that no emails get sent out when I save the user?

Thanks.

12条回答
放我归山
2楼-- · 2019-01-13 13:27

Disabling observers for Rails 3 it's simple:

Rails.configuration.active_record.observers = []
查看更多
女痞
3楼-- · 2019-01-13 13:28

There isn't a straightforward way to disable observers that I know of, but it sounds possible to add logic to your observer to not send an email when the activation code is set...

查看更多
beautiful°
4楼-- · 2019-01-13 13:35
User.skip_callback("create", :after, :send_confirmation_email)

....

User.set_callback("create", :after, :send_confirmation_email)

More on this:

Disabling Callbacks in Rails 3

查看更多
冷血范
5楼-- · 2019-01-13 13:36

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_something
end

and I just turn the flag on when needed

ActivityObserver.disabled=true
查看更多
走好不送
6楼-- · 2019-01-13 13:37

Another one you can try (rails 3)

config.active_record.observers = :my_model_observer unless File.basename($0) == 'rake'
查看更多
Summer. ? 凉城
7楼-- · 2019-01-13 13:38

You can take the method off the observer;

MessageObserver.send(:remove_method, :after_create)

Will stop the :after_create on MessageObserver by removing it.

查看更多
登录 后发表回答