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

rake, ruby, ruby-on-rails

Solution

TLDR;

task :t, [args] => [deps] 

Original Answer

When you pass in arguments to rake tasks, you can require the environment using the :needs option. For example:

desc "Testing environment and variables"
task :hello, :message, :needs => :environment do |t, args|
  args.with_defaults(:message => "Thanks for logging on")
  puts "Hello #{User.first.name}. #{args.message}"
end

Updated per @Peiniau's comment below

As for Rails > 3.1

task :t, arg, :needs => [deps] # deprecated

Please use

task :t, [args] => [deps] 

Problem

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?

Original source

Related problems