2012-09-11 61 views
14

在循环more than once内不可能对invoke执行相同的rake任务。但是,我希望能够调用rake first并循环访问一个数组,并在每次迭代时调用second使用不同的参数。由于invoke仅在第一次执行,因此我尝试使用execute,但Rake::Task#execute不使用splat(*)运算符,只接受一个参数。周围如何多次使用参数执行Rake任务?

desc "first task" 
task :first do 
    other_arg = "bar" 
    [1,2,3,4].each_with_index do |n,i| 
    if i == 0 
     Rake::Task["foo:second"].invoke(n,other_arg) 
    else 
     # this doesn't work 
     Rake::Task["foo:second"].execute(n,other_arg) 
    end 
    end 
end 

task :second, [:first_arg, :second_arg] => :prerequisite_task do |t,args| 
    puts args[:first_arg] 
    puts args[:second_arg] 
    # ... 
end 

一个黑客就是把参数execute到一个数组和second检查args来的结构,但似乎,那么,hackish的。是否有另一种(更好的)方法来完成我想要做的事情?

回答

19

您可以使用Rake :: Task#重新启用以允许它再次被调用。

desc "first task" 
task :first do 
    other_arg = "bar" 
    [1,2,3,4].each_with_index do |n,i| 
    if i == 0 
     Rake::Task["second"].invoke(n,other_arg) 
    else 
     # this does work 
     Rake::Task["second"].reenable 
     Rake::Task["second"].invoke(n,other_arg) 
    end 
    end 
end 

task :second, [:first_arg, :second_arg] do |t,args| 
    puts args[:first_arg] 
    puts args[:second_arg] 
    # ... 
end 

$耙第一

1 
bar 
2 
bar 
3 
bar 
4 
bar 
+0

看起来很漂亮。谢谢! –

4

execute功能要求一个Rake::TaskArguments作为参数,这就是为什么它只是接受一个参数。

You could use

stuff_args = {:match => "HELLO", :freq => '100' } 
Rake::Task["stuff:sample"].execute(Rake::TaskArguments.new(stuff_args.keys, stuff_args.values)) 

但是有调用和执行之间的另一个不同之处,执行不运行:当调用做到这一点首先prerequisite_task,所以调用和重新启用或执行不具有完全一样的含义。