Reputation: 16339
I want to pass multiple parameter but I don't know the numbers. Such as model names. How do I pass those parameters into a rake task and how do I access those parameters inside the rake task.
Like, $ rake test_rake_task[par1, par2, par3]
Upvotes: 35
Views: 28376
Reputation: 1970
Rake supports passing parameters directly to a task using an array, without using the ENV hack.
Define your task like this:
task :my_task, [:first_param, :second_param] do |t, args|
puts args[:first_param]
puts args[:second_param]
end
And call it like this:
rake my_task[Hello,World]
=> Hello
World
This article by Patrick Reagan on the Viget blog explains it nicely
Upvotes: 64
Reputation: 4789
You can use args.extras
to iterate over all the arguments without explicitly stating how many parameters you have.
Example:
desc "Bring it on, parameters!"
task :infinite_parameters do |task, args|
puts args.extras.count
args.extras.each do |params|
puts params
end
end
To run:
rake infinite_parameters['The','World','Is','Just','Awesome','Boomdeyada']
Output:
6
The
World
Is
Just
Awesome
Boomdeyada
Upvotes: 74
Reputation: 4026
Found this example on this blog post and the syntax seems a bit cleaner.
For example, if you had a say_hello
task, you could call it with any number of arguments, like so:
$ rake say_hello Earth Mars Venus
This is how it works:
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
Upvotes: 10
Reputation: 107
Use args.values.
task :events, 1000.times.map { |i| "arg#{i}".to_sym } => :environment do |t, args|
Foo.use(args.values)
end
Upvotes: 9
Reputation: 8100
You may try something like that:
rake test_rake_task SOME_PARAM=value1,value2,value3
And in rake task:
values = ENV['SOME_PARAM'].split(',')
Upvotes: 12