在我要从 Rails 3.2.22.4
升级的应用程序上至Rails 4.0.13
,以下用于增强全局环境任务的代码块由于无法在目标 Rails 版本上工作而成为障碍:
Rails.application.class.rake_tasks do
Rake::Task["environment"].enhance do
...
end
end
这在 3.2
上运行良好,但失败并显示 Don't know how to build task 'environment'
4.0
中的错误消息.
在 3.2 中,Rails.application.class.rake_tasks
返回 Proc object
( [#<Proc:0x007f978602a470@.../lib/rails/application.rb:301>]
) 指向 this line in the rails codebase 。在 4.0 上,它返回一个空数组。
上面提到的行 Proc object
似乎在 this commit 中被删除.
增强 environment
的首选方法是什么? rake 任务在Rails 4.x
?
上面这段代码在 lib/subdomain/rake.rb
中文件,它包含在 lib/subdomain/engine.rb
中的以下代码中:
module Subdomain
class Engine < Rails::Engine
...
rake_tasks do |_app|
require 'subdomain/rake'
end
...
end
end
Rake 任务无法执行,因为该命令因此错误而失败。 rails server|console
命令工作正常。
最佳答案
选项 1
如果我正确理解了这个问题,类似这样的事情应该通过将这些任务放置在像lib/tasks/environment.rake
这样的标准位置来工作。注意:这些都不是特定于 Rails 的。
# Re-opening the task gives the ability to extend the task
task :environment do
puts "One way to prepend behavior on the :environment rake task..."
end
task custom: :environment do
puts "This is a custom task that depends on :environment..."
end
task :environment_extension do
puts "This is another way to prepend behavior on the :environment rake task..."
end
# You can "enhance" the rake task directly too
Rake::Task[:environment].enhance [:environment_extension]
其输出将是:
$ rake custom
This is another way to prepend behavior on the :environment rake task...
One way to prepend behavior on the :environment rake task...
This is a custom task that depends on :environment...
选项 2
但是,问题仍然是为什么 :environment
需要扩展。如果要在 db:migrate
之前触发某些操作,您最好重新打开相关任务并为该特定任务添加另一个依赖项。例如:
task custom: :environment do
puts "This is a custom task that depends on :environment..."
end
task :custom_extension do
puts "This is a new dependency..."
end
# Re-opening the task in question allows you to added dependencies
task custom: :custom_extension
结果是:
$ rake custom
This is a new dependency on :custom
This is a custom task that depends on :environment...
C-C-C-组合破坏者!!
将所有内容组合起来,输出将如下所示:
$ rake custom
This is another way to prepend behavior on the :environment rake task...
One way to prepend behavior on the :environment rake task...
This is a new dependency on :custom
This is a custom task that depends on :environment...
关于ruby-on-rails - 加强全局环境任务 rails ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39398420/