Thursday, December 3, 2009

Bash script to easily check and switch between Rails environments. Usage: renv [p|d|t|s]

When I'm on our deployment server I'm constantly checking the RAILS_ENV environment variable to make sure that I don't accidentally do something on the production database when I meant to do it on the staging database. (Incidentally I’ve added some stuff to the Rakefile to guard against such a thing: Rakefile: Prevent destructive rake tasks in the production environment.). So I created this handy Bash function to check and switch between your Rails environments easily.

Sample usage:

$ renv
RAILS_ENV is unset
$ renv p
RAILS_ENV set to production
$ renv d
RAILS_ENV set to development
$ renv s
RAILS_ENV set to staging
$ renv t
RAILS_ENV set to test
$ renv
RAILS_ENV is test

And the code:

# Put this in your ~/.profile
function renv() {

  if [ $1 ];then
    eval 'rails_env=${rails_env_'"${1}"'}' 
    export RAILS_ENV=$rails_env
    echo "RAILS_ENV set to $RAILS_ENV" 
  elif [ $RAILS_ENV ];then
    echo "RAILS_ENV is $RAILS_ENV" 
    echo "RAILS_ENV is unset" 

No comments: