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

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

我找到了答案:

 tasks = Rake.application.tasks

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

正如您所写,使用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 

您可以像这样使用grep命令

 desc 'Test' task :test do # You can change db: by any other namespaces result = %x[rake -T | sed -n '/db:/{/grep/!p;}' | awk '{print$2}'] result.each_line do |t| puts t # Where t is your task name end end