Passing Command Line Arguments to Rake Tasks

Sometimes, we need to rake tasks that inserts a paticular user entered value into multiple databases.

We’d like to be able to pass this value into the rake task from the command line, or from another rake task, how can We do this?

1
2
3
4
5
require 'rake'

task :my_task, :arg1, :arg2 do |t, args|
  puts "Args were: #{args}"
end

You can invoke it by using the following:

1
2
3
task :invoke_my_task do
  Rake.application.invoke_task("my_task[1, 2]")
end

or if you prefer this syntax…

1
2
3
task :invoke_my_task_2 do
  Rake::Task[:my_task].invoke(3, 4)
end

A task with prerequisites passes its arguments to it prerequisites(tasks)

1
task :with_prerequisite, :arg1, :arg2, :needs => :my_task

or just a…

1
task :with_prerequisite, [:arg1, :arg2] => :my_task

To specify default values, we take advantage of args being a Rake::TaskArguments object

1
2
3
4
task :with_defaults, :arg1, :arg2 do |t, args|
  args.with_defaults(:arg1 => 1, :arg2 => 2)
  puts "Args with defaults were: #{args}"
end

Here are a few usages:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
> rake my_task[1,2]
Args were: {:arg1=>"1", :arg2=>"2"}

> rake "my_task[1, 2]"
Args were: {:arg1=>"1", :arg2=>"2"}

> rake invoke_my_task
Args were: {:arg1=>"1", :arg2=>"2"}

> rake invoke_my_task_2
Args were: {:arg1=>3, :arg2=>4}

> rake with_prerequisite[5,6]
Args were: {:arg1=>"5", :arg2=>"6"}

> rake with_prerequisite_2[7,8]
Args were: {:arg1=>"7", :arg2=>"8"}

> rake with_defaults
Args with defaults were: {:arg1=>:default_1, :arg2=>:default_2}

> rake with_defaults['x','y']
Args with defaults were: {:arg1=>"x", :arg2=>"y"}

For more information…

.

Any questions on this, please feel free to ask. We’re here to help…

Comments

Comments