Nuclear Rooster

5Jan/093

Rake task with arguments

I couldn't find a short, concise example of a rake task with arguments, so I decided to write one up for the world to see.

Firstly, the ability to add arguments was added somewhere along the line, so you might as well make sure you have a recent version of Rake:

nicks-computer:~ nick$ sudo gem install rake
Password:
Successfully installed rake-0.8.3
1 gem installed
Installing ri documentation for rake-0.8.3...
Installing RDoc documentation for rake-0.8.3...

Great. Now, lets dig in to an example rake file. You can put this in a file name 'Rakefile' anywhere you like, or in RAILS_ROOT/lib/tasks/some_file.rake if you are rails-ish.

desc "An example task that uses a single argument"
task :example_with_argument, :arg1 do |t, args|
  puts "Running 'example_with_argument' with '#{args.arg1}' as the argument"
end

desc "An example task that uses multiple arguments"
task :example_with_multiple_arguments, :arg1, :arg2 do |t, args|
  puts "Running 'example_with_argument' with '#{args.arg1}' and '#{args.arg2}' as the arguments"
end

desc "An example task that uses multiple arguments, and has defaults"
task :example_with_multiple_arguments_and_defaults, :arg1, :arg2 do |t, args|
  args.with_defaults(:arg1 => 'default_arg1', :arg2 => 'default_arg2')
  puts "Running 'example_with_argument' with '#{args.arg1}' and '#{args.arg2}' as the arguments"
end

Now, for how to run them. Without specifying arguments, the defaults (or an empty string if no defaults are specified) will be used:

nicks-computer:~ nick$ rake example_with_multiple_arguments_and_defaults
(in /Users/nick)
Running 'example_with_argument' with 'default_arg1' and 'default_arg2' as the arguments
nicks-computer:~ nick$ rake example_with_multiple_arguments_and_defaults[myarg1, myarg2]
(in /Users/nick)
Running 'example_with_argument' with 'myarg1' and 'myarg2' as the arguments

TaDa!

UPDATE:

Rake a a great tool, and widely used, but there are some new tools that surpass rake in some areas. For example check out Thor and how OpsCode uses it with their Knife tool.

Tagged as: , Leave a comment
Comments (3) Trackbacks (0)
  1. Hi there, how can I use this approach to tasks needing environment?

    Like this example:

    desc “Sample”
    task :create => :environment do
    puts “something”
    end

  2. This is in reply to Rikas question; better late than never.

    I needed to pass args to my task as well and it’s a matter of spacing, believe it or not. In your task you would have:

    desc “Something”
    task :foo => :environment do
    my_arg = ENV['MY_ARG']
    ….
    end

    Then when you do rake on the command line you use:

    rake foo MY_ARG=’value’

    There must be no in the assignment. I don’t now if all caps are required, but why not?


Leave a comment


No trackbacks yet.