I have a rake task that needs to insert a value into multiple databases.
I'd like to pass this value into the rake task from the command line, or from another rake task.
How can I do this?
I have a rake task that needs to insert a value into multiple databases.
I'd like to pass this value into the rake task from the command line, or from another rake task.
How can I do this?
You can specify formal arguments in rake by adding symbol arguments to the task call. For example:
Then, from the command line:
As demonstrated in the second example, if you want to use spaces, the quotes around the target name are necessary to keep the shell from splitting up the arguments at the space.
Looking at the code in rake.rb, it appears that rake does not parse task strings to extract arguments for prerequisites, so you can't do
task :t1 => "dep[1,2]"
. The only way to specify different arguments for a prerequisite would be to invoke it explicitly within the dependent task action, as in:invoke_my_task
and:invoke_my_task_2
.Note that some shells (like zsh) require you to escape the brackets:
rake my_task\['arg1'\]
I've found the answer from these two websites: Net Maniac and Aimred.
You need to have version > 0.8 of rake to use this technique
The normal rake task description is this:
To pass arguments, do three things:
To access the arguments in the script, use args.arg_name
To call this task from the command line, pass it the arguments in []s
will output
and if you want to call this task from another task, and pass it arguments, use invoke
then the command
will output
I haven't found a way to pass arguments as part of a dependency, as the following code breaks:
I like the "querystring" syntax for argument passing, especially when there are a lot of arguments to be passed.
Example:
The "querystring" being:
Warning: note that the syntax is
rake "mytask[foo=bar]"
and NOTrake mytask["foo=bar"]
When parsed inside the rake task using
Rack::Utils.parse_nested_query
, we get aHash
:(The cool thing is that you can pass hashes and arrays, more below)
This is how to achieve this:
Here's a more extended example that I'm using with Rails in my delayed_job_active_record_threaded gem:
Parsed the same way as above, with an environment dependency (in order load the Rails environment)
Gives the following in
options
Actually @Nick Desjardins answered perfect. But just for education: you can use dirty approach: using
ENV
argumentI just wanted to be able to run:
Simple, right? (Nope!)
Rake interprets
arg1
andarg2
as tasks, and tries to run them. So we just abort before it does.Take that, brackets!
Disclaimer: I wanted to be able to do this in a pretty small pet project. Not intended for "real world" usage since you lose the ability to chain rake tasks (i.e.
rake task1 task2 task3
). IMO not worth it. Just use the uglyrake task[arg1,arg2]
.