仅为 Rake 任务运行初始化程序 [英] Run initializer only for Rake tasks
问题描述
我希望在执行 Rake 任务时运行某个初始化程序,但在运行 Rails 服务器时不运行.
I'd like a certain initializer to run when executing a Rake task, but not when running the Rails server.
区分 Rake 调用和服务器调用的最佳方法是什么?
What is the best way to differentiate a Rake invocation and a server invocation?
推荐答案
Rake 允许您指定任务的依赖项.最好的推荐操作是将特定于 rake 的初始化放在它自己的任务中,而该任务又取决于环境"任务.例如:
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
如果你想创建一个特定于 rake 的初始化脚本目录,就像我们为 rails 所做的那样,我们只需在我们的 :custom_environment
任务中实现它.
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
这允许您将特定于 rake 的初始化器与常规初始化器分开.您只需要记住依赖于您设置的 :custom_environment
.
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.
这篇关于仅为 Rake 任务运行初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!