12

It is very surprising that Rails's initializers run while running any rake task, including db:migrate and db:seed.

An initializer in my app starts a background thread (a kind of worker process), and it should be executed only when the application is running in debug and production mode.

How to prevent a specific initializer from running when doing rake db:migrate or how to detect in initializer that a rake task is running?

Paul
  • 25,812
  • 38
  • 124
  • 247
  • 2
    Migrates need to load your environment, initializers are an integral part of an environment. If you need an initializer not to run during migrates then it's probably in the wrong place. – Matt Jun 10 '14 at 08:34

3 Answers3

10

If your initializer depends on the creaton of a specific table, one alternative is to check using ActiveRecord::Base.connection.table_exists? :mytable.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • 1
    A heads up to future folks that this does not work when running `db:create` as `ActiveRecord::Base.connection...` will cause an error complaining that the database does not exist. – Fralcon Jul 28 '21 at 22:02
  • to use this and be able to drop/create databases just rescue the `ActiveRecord::NoDatabaseError`. def initialize begin if ActiveRecord::Base.connection.table_exists? :your_table < some code that gets run..... > end rescue ActiveRecord::NoDatabaseError => exception # puts "error......#{exception.to_s}" end end – random_user_0891 Jun 27 '22 at 15:26
8

Here is a solution how to prevent an initializer from running in Rake task:

unless ( File.basename($0) == 'rake')
   # Initializer code
end
Paul
  • 25,812
  • 38
  • 124
  • 247
  • 4
    This _obviously_ depends on invoking it with "rake". If you are starting to use "rails" for the command `rails db:migrate` or some such, this will not work. – traday May 08 '17 at 17:00
1

Migrates need to load your environment, initializers are an integral part of an environment. If you need an initializer not to run during migrates then it's probably in the wrong place.

If you can't move it elsewhere then perhaps this answer (create a 'fast migrate' rake task) will help.

Community
  • 1
  • 1
Matt
  • 13,948
  • 6
  • 44
  • 68
  • 10
    Matt, what is this "elsewhere"? Requirements: I need to run a thread on application start and don't need it when migrating. Where to place thread start to NOT have to deal with additional command line parameters, as in that answer about fast migration? – Paul Jun 10 '14 at 08:54