Rake tasks with arguments

After a little digging and a little time to RTFM, I finally have a working rake task with arguments. The interesting thing about it is that Rake will not pass arguments to a task that is not expecting them. “Expecting them” takes the form of actually passing them as an argument to the task method right after the name. If you want to have defaults you will have to call with_defaults on the incoming args hash. Its a little weird but that’s how it works.

namespace :mike do
  desc "Playing with Rake arguments"
  task :test, [:arg1, :arg2] do |task, args|
    args.with_defaults(arg1: "foo", arg2: "bar")
    puts args.inspect

That task can be invoked from code like this:

Rake::Task["mike:test"].invoke("Fizz", "Buzz")

Unfortunately the space between the arguments means that running it from the command line requires quotes:

rake "mike:test[Fizz, Buzz]"

As nice as it is to have figured this out, I think the real question at this point is “Why am I not making this thing a class in my application?”, which of course I should be…

Ahh well, at least this will be here for some future project when I have a convincing answer to that.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s