Why Some Rake Tasks Require :environment

19 December 2012

If you look at lib/tasks directory in your Rails app, you probably will find few .rake files. Those files allow you to run custom rake command like rake name:print:random_stuff.

If you look at those files, you might find that some of them look like this:

  task :print_username => :environment do
    puts User.first.name
  end

While some:

  task :print_random do
    puts 'random random random'
  end

With :environment your task will run will full Rails environment loaded. That's why you can do User.first.name if you have a User model. If you do it this way:

  task :print_username do
    puts User.first.name
  end

Then execute the task:

  rake print_username
  => uninitialized constant User

I tend to forget to include :environment then smack my head when I see the uninitialized constant error.

Depending on what you want to do, you should choose to load environment or not, accordingly.

« back