Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rake task w/ splat arguments

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
like image 446
Kyle Decot Avatar asked Sep 06 '13 14:09

Kyle Decot


1 Answers

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
like image 112
Stefan Avatar answered Nov 08 '22 14:11

Stefan