This question already has an answer here:
I am able to pass in arguments as follows:
desc "Testing args"
task: :hello, :user, :message do |t, args|
args.with_defaults(:message => "Thanks for logging on")
puts "Hello #{args[:user]}. #{:message}"
end
I am also able to load the current environment for a Rails application
desc "Testing environment"
task: :hello => :environment do
puts "Hello #{User.first.name}."
end
What I would like to do is be able to have variables and environment
desc "Testing environment and variables"
task: :hello => :environment, :message do |t, args|
args.with_defaults(:message => "Thanks for logging on")
puts "Hello #{User.first.name}. #{:message}"
end
But that is not a valid task call. Does anyone know how I can achieve this?
Just for completeness, here the example from the docs mentioned above:
Notes:
#with_defaults
call, obviously.Array
for your arguments, even if there is only one.Array
.args
is an instance ofRake::TaskArguments
.t
is an instance ofRake::Task
.While these solutions work, in my opinion this is overly complicated.
Also, if you do it this way in zsh, you'll get errors if the brackets in your array aren't escaped with '\'.
I recommend using the ARGV array, which works fine, is much simpler, and is less prone to error. E.g:
then
The only thing you need to keep in mind is that ARGV[0] is the process name, so use only ARGV[1..-1].
I realize that strictly speaking this does not answer the question, as it does not make use of :environment as part of the solution. But OP did not state why he included that stipulation so it might still apply to his use case.
Just to follow up on this old topic; here's what I think a current Rakefile (since a long ago) should do there. It's an upgraded and bugfixed version of the current winning answer (hgimenez):
This is how you invoke it (http://guides.rubyonrails.org/v4.2/command_line.html#rake):
For multiple arguments, just add their keywords in the array of the task declaration (
task :hello, [:a,:b,:c]...
), and pass them comma separated:Note: the number of arguments is not checked, so the odd planet is left out:)
TLDR;
Original Answer
When you pass in arguments to rake tasks, you can require the environment using the :needs option. For example:
Updated per @Peiniau's comment below
As for Rails > 3.1
Please use
An alternate way to go about this: use OS environment variables. Benefits of this approach:
I have a rake task which requires three command-line options. Here's how I invoke it:
That's very clean, simple, and just bash syntax, which I like. Here's my rake task. Also very clean and no magic:
This particular example doesn't show the use of dependencies. But if the
:import
task did depend on others, they'd also have access to these options. But using the normal rake options method, they wouldn't.