如何找到rake任务的源文件?

Til*_*dor 42 ruby rake ruby-on-rails

我知道您可以通过键入来查看所有可能的rake任务

rake -T
Run Code Online (Sandbox Code Playgroud)

但我需要知道一项任务到底是做什么的.从输出中,我如何找到实际具有任务的源文件?例如,我正在尝试查找db:schema:dump任务的源代码.

小智 78

我知道这是一个老问题,但无论如何:

rake -W
Run Code Online (Sandbox Code Playgroud)

这是在rake 0.9.0中引入的.

http://rake.rubyforge.org/doc/release_notes/rake-0_9_0_rdoc.html

支持-where(-W)标志,用于显示定义任务的位置.


Tom*_*itz 40

尽管其他人已经说过,您可以通过编程方式在rails应用程序中获取rake任务的源位置.要执行此操作,只需在代码中或从控制台运行以下内容:

# load all the tasks associated with the rails app
Rails.application.load_tasks

# get the source locations of actions called by a task
task_name = 'db:schema:load' # fully scoped task name
Rake.application[task_name].actions.map(&:source_location)
Run Code Online (Sandbox Code Playgroud)

这将返回为此任务执行的任何代码的源位置.您也可以使用#prerequisites而不是#source_location获取必备任务名称列表(例如"环境"等).

您还可以列出使用以下加载的所有任务:

Rake.application.tasks
Run Code Online (Sandbox Code Playgroud)

更新:请参阅下面的Magne的好答案.对于rake> = 0.9.0的版本,您可以使用它rake -W来显示rake任务的源位置.


Bob*_*man 6

不幸的是,没有程序化的方法来做到这一点.Rake任务可以从rails本身,lib/tasks或任何带有tasks目录的插件加载.

这应该抓住Rails本身内的大部分内容:

find . -name "*.rake" | xargs grep "whatever"
Run Code Online (Sandbox Code Playgroud)

至于db:schema:dump,这是来源:

desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
task :dump => :environment do
  require 'active_record/schema_dumper'
  File.open(ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb", "w") do |file|
    ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
  end
end
Run Code Online (Sandbox Code Playgroud)

它可以在rails 2.2.2 gem中的lib/tasks/database.rake的第242行找到.如果你有不同版本的Rails,只需搜索" namespace :schema".

你可能真的想要它的来源ActiveRecord::SchemaDumper,但我认为你应该毫不费力地找出它的来源.:-)