Ruby-on-rails 强制 Rake 任务在特定 Rails 环境中运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21554287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force Rake Task To Run in Specific Rails Environment
提问by Undistraction
I need to run a series of Rake tasks from another Rake task. The first three tasks need to be run in the development environment, but the final task needs to be run in the staging environment. The task has a dependency on :environmentwhich causes the Rails development environment to be loaded before the tasks run.
我需要从另一个 Rake 任务运行一系列 Rake 任务。前三个任务需要在开发环境中运行,但最后一个任务需要在暂存环境中运行。该任务依赖于:environment哪个导致在任务运行之前加载 Rails 开发环境。
However, I need the final task to be executed in the staging environment.
但是,我需要在登台环境中执行最终任务。
Passing a RAILS_ENV=stagingflag before invoking the rake task is no good as the environment has already loaded at this point and all this will do is set the flag, not load the staging environment.
RAILS_ENV=staging在调用 rake 任务之前传递标志是不好的,因为此时环境已经加载,所有这一切都只是设置标志,而不是加载临时环境。
Is there a way I can force a rake task in a specific environment?
有没有办法可以在特定环境中强制执行 rake 任务?
回答by kddeisz
I've accomplished this kind of this before, albeit not in the most elegant of ways:
我以前已经完成了这种操作,尽管不是以最优雅的方式:
task :prepare do
system("bundle exec rake ... RAILS_ENV=development")
system("bundle exec rake ... RAILS_ENV=development")
system("bundle exec rake ... RAILS_ENV=test")
system("bundle exec rake ... RAILS_ENV=test")
system("bundle exec rake ... RAILS_ENV=test")
system("bundle exec rake ... RAILS_ENV=test")
end
It's always worked for me. I'd be curious to know if there was a better way.
它总是对我有用。我很想知道是否有更好的方法。
回答by Matt Schwartz
The way I solved it was to add a dependency to set the rails env before the task is invoked:
我解决它的方法是在调用任务之前添加一个依赖项来设置 rails env:
namespace :foo do
desc "Our custom rake task"
task :bar => ["db:test:set_test_env", :environment] do
puts "Custom rake task"
# Do whatever here...
puts Rails.env
end
end
namespace :db do
namespace :test do
desc "Custom dependency to set test environment"
task :set_test_env do # Note that we don't load the :environment task dependency
Rails.env = "test"
end
end
end

