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() {
  rails_env_p="production" 
  rails_env_d="development" 
  rails_env_s="staging" 
  rails_env_t="test" 

  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" 
  else
    echo "RAILS_ENV is unset" 
  fi
}

No comments: