Sep 9, 2007

How to run rake tasks for non-development rails environments

I’ve found that parameters passed to rake tasks in the form “name=value” are converted into the environment variables. This magic is done by rake itself when parsing command-line parameters. It has an interesting consequence – you can run some db-oriented rake tasks for any of your ruby on rails environments. For instance, to migrate your production database to the latest version you can run:
rake db:migrate RAILS_ENV=production

This knowledge is also useful when writing custom rake tasks; you can access environment variables using predefined ENV hash (you can also access rake command line parameters using ARGV hash).