【问题标题】:Is it possible to get a list of all available rake tasks in a namespace?是否可以获得命名空间中所有可用 rake 任务的列表?
【发布时间】:2010-08-05 13:33:38
【问题描述】:

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

【问题讨论】:

    标签: ruby rake


    【解决方案1】:

    正如您所写,使用 Rake.application.tasks 您可以获得所有任务。

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

    您可以将任务限制在一个命名空间(任务 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
    

    【讨论】:

      【解决方案2】:

      我已经找到答案了:

      任务 = Rake.application.tasks

      这将返回一个可以检查的 Rake::Task 对象数组。更多详情http://rake.rubyforge.org/

      【讨论】:

      • 据我所见,在范围内查找东西没有帮助,但我认为,这应该很容易:Rake.application.tasks.reject{|task| task.scope != [:your, :scope] }
      • 就我而言(Rails),还需要运行AppName::Application.load_tasks 来填充Rake.application.tasks
      • 注意:这适用于 rake 任务,但不适用于 rails console (这不是批评——问题是关于在 rake 中获取此信息的具体问题任务,但它让我感到惊讶,所以我认为这对未来的读者来说是值得注意的。)
      【解决方案3】:

      你可以像这样使用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
      

      【讨论】:

      • 这真的是在范围内查找任务的唯一可能解决方案吗?!
      • 出壳真的很慢,为什么要绕路?
      猜你喜欢
      • 2022-11-26
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 2011-02-14
      • 2010-12-07
      • 1970-01-01
      相关资源
      最近更新 更多