Rake task with variable arguments

Hi,

I want to create a Rails rake task that can accept a varying number of
arguments. Ideally, I’d like the arguments to be optional, and I’d also
like to be able to specify 1 or more.

So, if I have the rake task my_task, like this:

task :do_something, :arg1 do |t, args|
puts args.inspect

some code goes here

end

I’s like to be able to execute this like this:

rake do_something

rake do_something[1]

rake do_something[1, 2, 4]

I’d like args to be an empty array in the first call, a one element
array in the second, and a 3 element array in the third. I think 0
arguments or 1 is simple – the way I’ve written the task above does
this much. But I don’t know how to get it to accept more than 1. Is
there a way to do this?

Thanks.

I have submitted the following Pull Request to add this functionality:
Support variable-length arguments for Tasks by dennisjbell · Pull Request #150 · jimweirich/rake · GitHub.

In analyzing the source, currently there is no place that stores the
argument values not associated with a ‘named’ argument, so they cannot
be retrieved after parsing. The patch keeps all the passed-in values
and makes them available via the #to_a method, or just the extra values
via the #extras method (ie, not the values that get associated with
named
arguments.

I have also devised a horrendous hack to get around this current
limitation:

Prepare the dummy args - supports up to 100 values

vargs = ((0…99).map {|i| (“arg%02d” % i).to_sym})
def vargs.join(*args)

This gets used to document the args in rake -T: be descriptive, ie:

“,,…,”
end
def vargs.map(&block)

This need to return self in order to have the above join work

This is only called in the set_arg_names block internally to convert

to symbols which it already is; make sure you don’t need to use it

yourself; if so, use collect instead

self
end

task :task_name, vargs do |t, args|

Pull all the used args out…

values = args.names.select {|n| !args[n].nil?}.collect {|n| args[n]}

Pop out the special values

target = values.shift
sources = values

Rest of task

end