Passing in Arguments to Rake – My Way

** This is an update from RubyHead post ***

I’ve seen many interesting ways to pass arguments to rake tasks. The fact of matter is, I really don’t like messing around with any constant or global variable. Here’s how I like to do it.

rake mytask:do_something 1 2 3

Arguments 1, 2, and 3 will be available in the task. Therefore, if you look at the arguments($*), you’ll see [“mytask:do_something”, “1”, “2”, “3”]. Just reject the first in the Array and you got yourself arguments

Here’s another example of passing in “Hash”. This is with quotes because there’s a bit of manipulation needed.

rake mytask:do_something setting:WHATEVER user:me

Using the argument facility built into Ruby, just create a hash inside of my task. I can even create a method to do this for all tasks. Below is my implementation.

desc "my task do something"
task :do_something => :environment do
  options = {}
  $*.each {|arg| options[arg.split(":")[0]] = arg.split(":")[1]}
  options.reject! {|k,v| v == "" || v.nil? }
  # I now have {"setting" => "WHATEVER", "user" => "me"}
  # for whatever I want to do.
  # ...


Make sure you have exit or it will try to run arguments as a series of tasks.

I think it’s cleaner and easier way to do it, but that’s just my opinion. By the way, $* has an alias, ARGV.