在我从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
会返回指向this line in the rails codebase的Proc object
([#<Proc:0x007f978602a470@.../lib/rails/application.rb:301>]
)。在4.0上,它返回一个空数组。
以上Proc object
中提及的行似乎已在this commit中删除。
在environment
中增强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
命令可以正常工作。
答案 0 :(得分:3)
如果我正确理解了这个问题,那么这样的事情应该可以通过将这些任务放在像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...
然而,问题仍然是为什么: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...
结合一切,输出如下:
$ 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...