What's the 'environment' task in Rake?
Asked Answered
V

3

148

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.

Vollmer answered 12/8, 2011 at 18:32 Comment(1)
Check out the new syntax #12493837Scleroderma
A
151

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".

Arenas answered 12/8, 2011 at 18:37 Comment(3)
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. github.com/rails/rails/blob/master/railties/lib/rails/tasks/…Keyboard
@Keyboard Looks like here: github.com/rails/rails/blob/v4.2.4/railties/lib/rails/…Radiolucent
Guess what chagpt can' answer thisEdomite
H
51

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.

Hummel answered 12/8, 2011 at 18:35 Comment(0)
P
50

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.

Pane answered 4/9, 2013 at 15:8 Comment(1)
The method of task's document is too simple to understand it.Accoucheur

© 2022 - 2024 — McMap. All rights reserved.