Run initializer only for Rake tasks

2020-06-19 18:05发布

问题:

I'd like a certain initializer to run when executing a Rake task, but not when running the Rails server.

What is the best way to differentiate a Rake invocation and a server invocation?

回答1:

Rake allows you to specify dependencies for your tasks. The best recommended action would be for you to put your rake-specific initialization in its own task that in turn depends on the "environment" task. For example:

namespace :myapp do
    task :custom_environment => :environment do
        # special initialization stuff here
        # or call another initializer script
    end

    task :my_task => :custom_environment do
        # perform actions that need custom setup
    end
end

If you want to make a rake-specific directory of initializer scripts like we have for rails proper, we would just implement that in our :custom_environment task.

task :custom_environment => :environment do
    Dir.glob("config/rake-initializers/*.rb").each do |initializer|
        require initializer
    end
end

This allows you to keep rake-specific intializers separate from the regular initializers. You just have to remember to depend on the :custom_environment you set up.