Reputation: 21618
I just wonder how to have dynamic (X) number of arguments passing to a rake task. for example I want to achieve this:
rake task:test[arg1,arg2,arg3,...]
So here the number of arguments are not fixed, it could be arg1..arg10
or arg1..arg20
or maybe less/more than this.
any idea?
P.S: I don't want to waste too much memory for this task, thus I'm looking for an optimal solution. Thanks.
Upvotes: 2
Views: 799
Reputation: 11
I don't know if you still need this, but here is my solution:
task :test, [:arg] do |t,args|
arguments = Array.new
arguments << args.arg
args.extras.each{|a| arguments << a}
puts arguments
end
Result:
rake test[arg1,arg2,arg3,arg4,...]
arg1
arg2
arg3
arg4
...
Upvotes: 1
Reputation: 27845
You can pre-define a maximum number of parameters, but you don't need to use all:
require 'rake'
myargs = 'p1'.upto('p20').map{ |x| x.to_sym }
task :test, myargs do |t, args|
puts "#{t}: #{args.inspect}"
end
Rake.application[:test].invoke(1,2,3,4,5,6,7,8)
The result:
test: {:p1=>1, :p2=>2, :p3=>3, :p4=>4, :p5=>5, :p6=>6, :p7=>7, :p8=>8}
If you need default values, you can define them:
task :test, myargs do |t, args|
args.with_defaults(:p19 => 'default1')
puts "#{t}: #{args.inspect}"
end
Result:
test: {:p19=>"default1", :p1=>1, :p2=>2, :p3=>3, :p4=>4, :p5=>5, :p6=>6, :p7=>7, :p8=>8}
Another way to define parameters witth default values:
myargs = Hash.new{|hash,key| hash[key] = "Default #{key}"}
20.times{|i| myargs[:"p#{i}"] }
task :test, myargs.keys do |t, args|
args.with_defaults(myargs)
puts "#{t}: #{args.inspect}"
end
Upvotes: 1