How do I execute Rake tasks with arguments multiple times?

前端 未结 4 1196
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-19 04:39

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

相关标签:
4条回答
  • 2021-02-19 04:52

    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.

    0 讨论(0)
  • 2021-02-19 04:58

    FWIW this might help someone so I'll post it.

    I wanted to be able to run one command from the CLI to run one Rake task multiple times (each time with new arguments, but that's not important).

    Example:

    rake my_task[x] my_task[y] my_task[z]
    

    However, since Rake sees all my_task as the same task regardless of the args, it will only invoke the first time my_task[x] and will not invoke my_task[y] and my_task[z].

    Using the Rake::Task#reenable method as mentioned in the other answers, I wrote a reenable Rake task which you can position to run after a task to allow it to run again.

    Result:

    rake my_task[x] reenable[my_task] my_task[y] reenable[my_task] my_task[z]
    

    I wouldn't say this is ideal but it works for my case.

    reenable Rake task source:

    task :reenable, [:taskname] do |_task, args|
      Rake::Task[args[:taskname]].reenable
      Rake::Task[:reenable].reenable
    end
    
    0 讨论(0)
  • 2021-02-19 05:11

    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
    
    0 讨论(0)
  • 2021-02-19 05:12

    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
    
    0 讨论(0)
提交回复
热议问题