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

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

Leave a Comment