Run Initializer for Rake Tasks Only

I want some initializer to start when the Rake task is executed, but not when the Rails server starts.

What is the best way to differentiate a Rake call from a server call?

+5
ruby-on-rails rake
source share
1 answer

Rake lets you specify dependencies for your tasks. The best recommended action is that you put your rake-related initialization in your own task, which 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 create a directory of initialization scripts like rake, as we have for the right rails, we would just implement this in our task :custom_environment .

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

This allows you to remove rake-specific intensifiers separately from regular initializers. You just have to remember that it depends on :custom_environment you created.

+6
source share

All Articles