13

I'm attempting to create a rake task that takes a required first argument, and then any number of additional arguments which I want to lump together into an array:

rake course["COURSE NAME", 123, 456, 789]

I've tried the following but args[:numbers] is simply a string w/ 123 instead of all of the numbers.

task :course, [:name, *:numbers] => :environment do |t, args|
  puts args # {:name=>"COURSE NAME", :numbers=>"123"}
end
Kyle Decot
  • 20,715
  • 39
  • 142
  • 263

1 Answers1

24

Starting with rake 10.1.0 you can use Rake::TaskArguments#extras:

task :environment

task :course, [:name] => :environment do |t, args|
  name = args[:name]
  numbers = args.extras
  puts "name = #{name}"
  puts "numbers = #{numbers.join ','}"
end

Output:

$ rake "course[COURSE NAME, 123, 456, 789]"
name = COURSE NAME
numbers = 123,456,789

For rake < 10.1.0 you could create a sufficienty large argument list.

Here's a workaround for up to 26 numbers:

task :course, [:name, *:a..:z] => :environment do |t, args|
  name = args[:name]
  numbers = args.values_at(*:a..:z).compact
  puts "name = #{name}"
  puts "numbers = #{numbers.join ','}"
end
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • This does not work. I've tried `rake course["COURSE NAME",123,456,789]` as well as `rake course["COURSE NAME",[123,456,789]]` and in both cases `args.extras` is `nil` – Kyle Decot Sep 06 '13 at 14:52
  • 1
    Seems like [this feature](https://github.com/jimweirich/rake/pull/150) was introduced in rake 10.1.0, maybe you have to update – Stefan Sep 06 '13 at 15:01
  • This works when using 10.1.0 our server is currently running 10.0.3. Is there a solution that doesn't use the `extras` method? – Kyle Decot Sep 06 '13 at 15:37
  • @KyleDecot added a hack for rake < 10.1.0 to my answer – Stefan Sep 06 '13 at 16:12