如何将多个参数传递给rake任务

kru*_*hah 29 ruby rake

我想传递多个参数,但我不知道数字.比如模型名称.如何将这些参数传递给rake任务,以及如何在rake任务中访问这些参数.

喜欢, $ rake test_rake_task[par1, par2, par3]

Hen*_*dge 61

Rake支持使用数组直接将参数传递给任务,而不使用ENV hack.

像这样定义你的任务:

task :my_task, [:first_param, :second_param] do |t, args|
  puts args[:first_param]
  puts args[:second_param]
end
Run Code Online (Sandbox Code Playgroud)

并称之为:

rake my_task[Hello,World]
=> Hello
   World
Run Code Online (Sandbox Code Playgroud)

Patrick Reagan在Viget博客上发表的这篇文章很好地解释了这一点

  • 这没有回答这个问题.OP表示他不知道传递的参数数量. (15认同)

Ard*_*ram 60

您可以使用args.extras迭代所有参数,而无需明确说明您拥有的参数数量.

例:

desc "Bring it on, parameters!"
task :infinite_parameters do |task, args| 
    puts args.extras.count
    args.extras.each do |params|
        puts params
    end         
end
Run Code Online (Sandbox Code Playgroud)

跑步:

rake infinite_parameters['The','World','Is','Just','Awesome','Boomdeyada']
Run Code Online (Sandbox Code Playgroud)

输出:

6
The
World
Is
Just
Awesome
Boomdeyada
Run Code Online (Sandbox Code Playgroud)

  • 这绝对应该是答案. (2认同)

les*_*est 11

你可以尝试这样的事情:

rake test_rake_task SOME_PARAM=value1,value2,value3
Run Code Online (Sandbox Code Playgroud)

在rake任务中:

values = ENV['SOME_PARAM'].split(',')
Run Code Online (Sandbox Code Playgroud)


Ser*_*gei 8

使用args.values.

task :events, 1000.times.map { |i| "arg#{i}".to_sym } => :environment do |t, args|
  Foo.use(args.values)
end
Run Code Online (Sandbox Code Playgroud)


Gau*_*tam 8

在这篇博客文章中找到了这个例子,语法似乎有点清晰.

例如,如果您有say_hello任务,可以使用任意数量的参数调用它,如下所示:

$ rake say_hello Earth Mars Venus
Run Code Online (Sandbox Code Playgroud)

这是它的工作原理:

task :say_hello do
  # ARGV contains the name of the rake task and all of the arguments.
  # Remove/shift the first element, i.e. the task name.
  ARGV.shift

  # Use the arguments
  puts 'Hello arguments:', ARGV

  # By default, rake considers each 'argument' to be the name of an actual task. 
  # It will try to invoke each one as a task.  By dynamically defining a dummy
  # task for every argument, we can prevent an exception from being thrown
  # when rake inevitably doesn't find a defined task with that name.
  ARGV.each do |arg|
    task arg.to_sym do ; end
  end

end
Run Code Online (Sandbox Code Playgroud)