是否可以获取命名空间中所有可用rake任务的列表?

ste*_*enr 19 ruby rake

是否可以从rake任务中获取命名空间中的任务列表?一种程序化的'rake -T db'?

ste*_*enr 17

我找到了答案:

tasks = Rake.application.tasks

这将返回一个可以检查的Rake :: Task对象数组.有关详细信息,请访问http://rake.rubyforge.org/

  • 在我的情况下(Rails),还有必要运行`AppName :: Application.load_tasks`来填充`Rake.application.tasks` (2认同)

knu*_*nut 12

正如您所写,使用Rake.application.tasks可以完成所有任务.

但是在命名空间内,您只能选择命名空间的任务(task mytest:tasklist)

您可以将任务限制为命名空间(task tasklist_mytest).

require 'rake'

namespace :mytest do |ns|

  task :foo do |t|
    puts "You called task #{t}"
  end

  task :bar do |t|
    puts "You called task #{t}"
  end

  desc 'Get tasks inside actual namespace'
  task :tasklist do
    puts 'All tasks of "mytest":'
    puts ns.tasks #ns is defined as block-argument
  end

end

desc 'Get all tasks'
task :tasklist do
  puts 'All tasks:'
  puts Rake.application.tasks
end

desc 'Get tasks outside the namespace'
task :tasklist_mytest do
  puts 'All tasks of "mytest":'
  Rake.application.in_namespace(:mytest){|x|
    puts x.tasks
  }
end

if $0 == __FILE__
  Rake.application['tasklist'].invoke()  #all tasks
  Rake.application['mytest:tasklist'].invoke() #tasks of mytest
  Rake.application['tasklist_mytest'].invoke() #tasks of mytest
end
Run Code Online (Sandbox Code Playgroud)