如何在rake多任务中传递不同的参数

时间:2014-06-27 07:13:10

标签: ruby-on-rails ruby rake rake-task

我想为每个方法传递不同的参数,并且需要使用rake task

并行运行所有方法

这是rake任务调用示例

Rake::Task['test:sync'].invoke(user.id, user.address)
Rake::Task['test:sync'].invoke(user.id, user.address)
Rake::Task['test:sync'].invoke(user.id, user.address)

我已经看过像这样的多任务示例

multitask :copy_files => [:copy_src, :copy_doc, :copy_bin] do
    puts "All Copies Complete"
end

他们在这里只使用任务名称进行调用。但在我的情况下,我想传递带参数的任务名称。我怎样才能实现它。

1 个答案:

答案 0 :(得分:1)

将功能提取到自己的方法(foo)中,并使用烘焙到任务名称本身的参数(arg1arg2)动态声明rake任务。然后声明multitask并调用它。所有对foo的调用都将并行运行。

def foo(arg1, arg2)
  thread_id = Thread.current.object_id.to_s[-4..-1]
  10.times do |i|
    sleep rand
    puts "[#{thread_id}] (#{arg1}) (#{arg2}) (#{i})"
  end
end

task :parallel_foos do
  arg1s = (1..4).map { sprintf('%.4f', rand) }
  arg2s = %w{red green blue yellow}
  arg_pairs = arg1s.zip(arg2s)
  # dynamically declare unique rake tasks
  arg_pairs.each do |arg_pair|
    task arg_pair.to_s do
      foo(*arg_pair)
    end
  end
  multitask :_parallel_foos => arg_pairs.map(&:to_s)
  Rake::MultiTask[:_parallel_foos].invoke
end

>> rake parallel_foos
[2460] (0.4510) (blue) (0)
[4820] (0.5997) (yellow) (0)
[4820] (0.5997) (yellow) (1)
[2980] (0.3482) (red) (0)
[2980] (0.3482) (red) (1)
[2100] (0.2251) (green) (0)
[2980] (0.3482) (red) (2)
[4820] (0.5997) (yellow) (2)
[2460] (0.4510) (blue) (1)
[2980] (0.3482) (red) (3)
[4820] (0.5997) (yellow) (3)
[2100] (0.2251) (green) (1)
[2980] (0.3482) (red) (4)
[2100] (0.2251) (green) (2)
[2460] (0.4510) (blue) (2)
[2100] (0.2251) (green) (3)
[4820] (0.5997) (yellow) (4)
[2460] (0.4510) (blue) (3)
[2980] (0.3482) (red) (5)
[4820] (0.5997) (yellow) (5)
[2460] (0.4510) (blue) (4)
[2980] (0.3482) (red) (6)
[2100] (0.2251) (green) (4)
[2460] (0.4510) (blue) (5)
[4820] (0.5997) (yellow) (6)
[2100] (0.2251) (green) (5)
[2980] (0.3482) (red) (7)
[2460] (0.4510) (blue) (6)
[4820] (0.5997) (yellow) (7)
[2980] (0.3482) (red) (8)
[2100] (0.2251) (green) (6)
[4820] (0.5997) (yellow) (8)
[2460] (0.4510) (blue) (7)
[2100] (0.2251) (green) (7)
[2980] (0.3482) (red) (9)
[2460] (0.4510) (blue) (8)
[4820] (0.5997) (yellow) (9)
[2460] (0.4510) (blue) (9)
[2100] (0.2251) (green) (8)
[2100] (0.2251) (green) (9)