145

According to "Custom Rake Tasks":

desc "Pick a random user as the winner"
task :winner => :environment do
  puts "Winner: #{pick(User).name}"
end

As far as I know, the :winner => :environment means "do environment before winner". But what's environment? When should I use it?

I tried rake -T, but in the list I couldn't find environment.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Lai Yu-Hsuan
  • 27,509
  • 28
  • 97
  • 164

3 Answers3

150

You can get access to your models, and in fact, your whole environment by making tasks dependent on the environment task. This lets you do things like run rake RAILS_ENV=staging db:migrate.

See "Custom Rake Tasks".

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Sameer C
  • 2,777
  • 1
  • 18
  • 12
  • 4
    Where is it defined in the source? I found where the rake tasks are, and I found an empty task definition that depends on 'app:environment', but I can't find the definition of the app:environment task. https://github.com/rails/rails/blob/master/railties/lib/rails/tasks/engine.rake – odigity Jan 27 '15 at 20:18
  • 4
    @odigity Looks like here: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application.rb#L454 – Carson Reinke Sep 04 '15 at 15:39
  • Guess what chagpt can' answer this – Almokhtar Jan 20 '23 at 05:01
50

It loads in your Rails environment so you can actually use your models and what not. Otherwise, it has no idea about those things.

So if you made a task that just did puts "HI!" then you don't need to add the :environment task to the dependencies. But if you wish to do something like User.find(1) well that will need it.

MrDanA
  • 11,489
  • 2
  • 36
  • 47
47

Including => :environment will tell Rake to load full the application environment, giving the relevant task access to things like classes, helpers, etc. Without the :environment, you won't have access to any of those extras.

Also => :environment itself does not make available any environment-related variables, e.g. environment, @environment, RAILS_ENV, etc.

Lars Levie
  • 795
  • 6
  • 9