Rake task w/ splat arguments
Asked Answered
H

1

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
Hinds answered 6/9, 2013 at 14:33 Comment(4)
How about rake course["COURSE NAME", [123, 456, 789]]?Cutcherry
That gives me {:name=>"COURSE NAME", :numbers=>"[123"} which is really bizarre.Hinds
No spaces are allowed between the arguments for the tasks, try this: rake course["COURSE NAME",123,456,789]Light
Nope. Gives me {:name=>"COURSE NAME", :numbers=>"123"}Hinds
B
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
Butt answered 6/9, 2013 at 14:47 Comment(4)
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 nilHinds
Seems like this feature was introduced in rake 10.1.0, maybe you have to updateButt
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?Hinds
@KyleDecot added a hack for rake < 10.1.0 to my answerButt

© 2022 - 2024 — McMap. All rights reserved.