Run initializer only for Rake tasks

痴心易碎 提交于 2019-12-09 12:59:37

问题


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.



来源:https://stackoverflow.com/questions/4323632/run-initializer-only-for-rake-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!