Simple Way of Turning Off Observers During Rake Task

Simple way of turning off observers during rake task?

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
#whatever
end

Then, in the observer:

def after_save(user)
return if user.skip_activation
#rest of stuff to send email
end

Simple way of turning off observers during rake task?

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
#whatever
end

Then, in the observer:

def after_save(user)
return if user.skip_activation
#rest of stuff to send email
end

Rails Observers, Plugins and Migrations are in a race, who wins?

I haven't found a decent way to disable Observers at run time. This has been previously discussed in Simple way of turning off observers during rake task?

However, I guess you could "unplug" the plugin code from your model by redefining the troublesome model in your migration:

class YourMigration < ActiveRecord::Migraation
class YourModel < ActiveRecord::Base; end

def self.up
...
end

def self.down
...
end
end

Rake task failing: Environment not loading

I found a solution that seems to work for me. I found...

Simple way of turning off observers during rake task?

I used...

Rails.configuration.active_record.observers = []

...in my rake task to disable observers. So my complete rake task now looks like...

task :send_reminder_emails => :environment do
Rails.configuration.active_record.observers = []
Registration.send_reminder_emails
end

...I just run bundle exec rake send_reminder_emails to run the rake task...

Execute the rake task for longer data

Do you have any sort of background job gem that you are using (eg. delayed_job)? If so, I would have a rake task that creates a bunch of background jobs to do the work.

If you have an array you are iterating through, you could do it like:

items.in_groups_of(10000, false) do |batch|
# create background job for this batch
end

If it's a collection, you can use something like:

@items.find_in_batches(batch_size: 10000) do |batch|
# create background job for this batch
end

How do I disable cache sweepers for testing purposes

I was able to use the no-peeping-toms gem to block observers during testing.

NOTE: This also works for rake tasks. I had an issue with observers being called during a migration and this solved it.



Related Topics



Leave a reply



Submit