How to pass arguments into a Rake task with environment in Rails?

Will picture Will · Aug 31, 2009 · Viewed 95.2k times · Source

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?

Answer

inger picture inger · Mar 22, 2011

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):

desc "Testing environment and variables"
task :hello, [:message]  => :environment  do |t, args|
  args.with_defaults(:message => "Thanks for logging on")
  puts "Hello #{User.first.name}. #{args.message}"   # Q&A above had a typo here : #{:message}
end

This is how you invoke it (http://guides.rubyonrails.org/v4.2/command_line.html#rake):

  rake "hello[World]" 

For multiple arguments, just add their keywords in the array of the task declaration (task :hello, [:a,:b,:c]...), and pass them comma separated:

  rake "hello[Earth,Mars,Sun,Pluto]" 

Note: the number of arguments is not checked, so the odd planet is left out:)