2

在我要从 升级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>]) 指向rails 代码库中的这一行。在 4.0 上,它返回一个空数组。

上面提到的那一行Proc object似乎在这个 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命令工作正常。

4

1 回答 1

3

选项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需要扩展。如果要在 a 之前触发某些内容,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...

CCC-组合断路器!!

结合所有内容,输出将如下所示:

$  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...
于 2016-09-09T17:18:51.580 回答