我想传递多个参数,但我不知道数字。比如模型名称。如何将这些参数传递给rake任务,以及如何在rake任务中访问这些参数。
赞,$ rake test_rake_task[par1, par2, par3]
答案 0 :(得分:61)
Rake支持使用数组直接将参数传递给任务,而不使用ENV hack。
像这样定义你的任务:
task :my_task, [:first_param, :second_param] do |t, args|
puts args[:first_param]
puts args[:second_param]
end
并称之为:
rake my_task[Hello,World]
=> Hello
World
This article by Patrick Reagan on the Viget blog explains it nicely
答案 1 :(得分:53)
您可以使用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
运行:
rake infinite_parameters['The','World','Is','Just','Awesome','Boomdeyada']
输出:
6
The
World
Is
Just
Awesome
Boomdeyada
答案 2 :(得分:11)
您可以尝试这样的事情:
rake test_rake_task SOME_PARAM=value1,value2,value3
在rake任务中:
values = ENV['SOME_PARAM'].split(',')
答案 3 :(得分:8)
使用args.values。
task :events, 1000.times.map { |i| "arg#{i}".to_sym } => :environment do |t, args|
Foo.use(args.values)
end
答案 4 :(得分:8)
在此blog post 上找到此示例,语法似乎更清晰。
例如,如果你有一个say_hello
任务,你可以使用任意数量的参数调用它,如下所示:
$ rake say_hello Earth Mars Venus
这是它的工作原理:
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