【发布时间】:2010-08-05 13:33:38
【问题描述】:
是否有可能从 rake 任务中 获取命名空间中的任务列表?一种程序化的“rake -T db”?
【问题讨论】:
是否有可能从 rake 任务中 获取命名空间中的任务列表?一种程序化的“rake -T db”?
【问题讨论】:
正如您所写,使用 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
【讨论】:
我已经找到答案了:
任务 = Rake.application.tasks这将返回一个可以检查的 Rake::Task 对象数组。更多详情http://rake.rubyforge.org/
【讨论】:
AppName::Application.load_tasks 来填充Rake.application.tasks
rails console。 (这不是批评——问题是关于在 rake 中获取此信息的具体问题任务,但它让我感到惊讶,所以我认为这对未来的读者来说是值得注意的。)
你可以像这样使用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
【讨论】: