增强全球环境任务轨道

时间:2016-09-08 19:04:17

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 rake rails-4-upgrade

在我从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 codebaseProc 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命令可以正常工作。

1 个答案:

答案 0 :(得分: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需要延长。如果要在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-Combo Breaker !!

结合一切,输出如下:

$  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...