Passing multiple options/argument with default options in rake

Rake task allows you to accept multiple arguments which can be used within the task, and also allows us to specify default options for these arguments.

Accept multiple arguments/options

Lets say we have a simple rake task to sync data from/across our servers to different enviroments.

We can accept the server and host as arguments here.

namespace :db do
  desc "Restores the database dump to the given environment"
  task :sync, [:server, :host] => [:environment, 'db:drop', 'db:create'] do |_t, args|

    ...

  end
end

The above rake task can be called using:

bin/rake 'db:sync[staging, local]'
With default values

Sometimes it makes sense to have default values for the arguments. An eg use case would be if no value is specified for the host, we are expecting the DB to be synced to our local database. In such situations, we can use args.with_defaults

namespace :db do
  desc "Restores the database dump to the given environment"
  task :sync, [:server, :host] => [:environment, 'db:drop', 'db:create'] do |_t, args|
    args.with_defaults(:server => 'staging', :host => 'local')

    ....
  
  end
end

and the rake task can be executed using:

bin/rake 'db:sync[staging]'
Note:

if you are using zsh, you will need to wrap the task inside ' '. this is because zsh doesn't play too nicely with the arguments/commands.