testomatic

Rake tasks, options and arguments

I’ve been starting to use rake more and more recently. I find it to be a little more flexible than my old favourite build tool ant. The ability to use all existing ruby gems and jump straight into ruby code is very flexible, but it still maintains the structure necessary for a practical build file. And hey, if it’s good enough for Martin Fowler then it’s good enough for me right?

Here’s a few tips I found out whilst working on a recent build file, namely setting options via the command line and passing arguments to your tasks.

Passing command line options to rake

This one is useful for setting global options, a little bit analogous to -Dproperty=value for those of us from an ant background.

rake mytask foo=bar

You can then pick up these options from the ENV hash in your rake file.

task :mytask do
    puts ENV["foo"]
end

Passing an argument to a rake task via the command line

Passing arguments to specific commands allows you a bit more control over your build files. In the below example we pass two arguments with the values foo and bar through to our task.

rake mytask[foo, bar]

These can be picked up like this

task :mytask, :arg1, :arg2 do |t, args|
    puts args[:arg1]
    puts args[:arg2]	
end

Or if you have dependancies associated with your task the syntax is slightly different.

task :mytask, [:arg1, :arg2] => [:task, :another_task] do |t, args|
    puts args[:arg1]
    puts args[:arg2]	
end

And if you need some defaults you can add those too …

task :mytask, [:arg1, :arg2] => [:task, :another_task] do |t, args|
    args.with_defaults(:arg1 => 'some value', :arg2 => 'another value')
    puts args[:arg1]
    puts args[:arg2]	
end

Comment

blog comments powered by Disqus

Recent posts