How do I execute Rake tasks with arguments multiple times?

余生长醉 提交于 2019-12-12 08:21:32

问题


It's not possible to invoke the same rake task from within a loop more than once. But, I want to be able to call rake first and loop through an array and invoke second on each iteration with different arguments. Since invoke only gets executed the first time around, I tried to use execute, but Rake::Task#execute doesn't use the splat (*) operator and only takes a single argument.

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

One hack around it is to put the arguments to execute into an array and in second examine the structure of args, but that seems, well, hackish. Is there another (better?) way to accomplish what I'd like to do?


回答1:


You can use Rake::Task#reenable to allow it to be invoked again.

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

$ rake first

1
bar
2
bar
3
bar
4
bar



回答2:


The execute function asks for a Rake::TaskArguments as a parameter, this is why it only accepts one argument.

You could use

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

However there is another difference between invoke and execute, execute doesn't run the :prerequisite_task when invoke does this first, so invoke and reenable or execute doesn't have exactly the same meaning.




回答3:


This worked for me, it's quite easy to understand you just need to loop you bash command.

task :taskname, [:loop] do |t, args|
        $i = 0
        $num = args.loop.to_i
        while $i < $num  do
        sh 'your bash command''
        $i +=1
        end
    end


来源:https://stackoverflow.com/questions/12379026/how-do-i-execute-rake-tasks-with-arguments-multiple-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!