Passing Arguments to a Rails Rake Task

I had to make a Rake task today which accepted command line arguments. It took me 45 minutes of googling to find a syntax that actually worked with Rails.

Assuming your task is seeder:seed and you want to pass in a number as an argument:

namespace :seeder do
  desc "create random employees"
  task :seed, [:amount] => :environment do |task, args|
    puts "Your amount is #{args.amount}"
  end
end

And from the command line, you pass in the arguments using an array-like syntax:

rake seeder:seed[100]

Strings are not enclosed in quotes when being passed in on the command line.

Also, an interesting gotcha is that when you pass in multiple arguments they must be separated by commas but without any whitespace between them.

This works:

rake seeder:seed[100,citibank]

This does not:

rake seeder:seed[100, citibank]