Is it possible to get a list of all available rake tasks in a namespace?

后端 未结 3 552
名媛妹妹
名媛妹妹 2020-12-31 02:13

Is it possible from within a rake task to get a list of tasks in a namespace? A sort of programatic \'rake -T db\' ?

相关标签:
3条回答
  • 2020-12-31 02:16

    I've found out the answer:

    tasks = Rake.application.tasks
    

    This will return an array of Rake::Task objects that can be examined. Further details at http://rake.rubyforge.org/

    0 讨论(0)
  • 2020-12-31 02:24

    You can use the grep command like this

    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
    
    0 讨论(0)
  • 2020-12-31 02:29

    As you wrote, with Rake.application.tasks you get all tasks.

    But inside the namespace, you can select only the tasks of the namespace (task mytest:tasklist)

    And you may restrict the tasks to a namespace (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
    
    0 讨论(0)
提交回复
热议问题