Jacob Swanner Development Blog

Common Rails command shortcuts

I know many people – including myself – use Bash aliases for common command line tasks. Some popular examples would be: ss short for script/server, sc for script/console, and sg for script/generate.

These are setup by putting the following code in a Bash configuration file – such as ~/.bash_login:

alias ss='script/server'
alias sc='script/console'
alias sg='script/generate'

That works great, until you switch to Rails 3; all of these script files have been removed, and you use the rails command in their place: rails server instead of script/server, rails console instead of script/console, etc. Rails 3 provides shortcuts for the common commands: rails s is short for rails server, rails c is short for rails console, and so on. Some have suggested aliasing the rails command to just r, allowing you to use r s to start a server.

These shortcuts are nice, and is much less typing. But, I don’t want to have to remember when I’m in a Rails 2 app to use ss and then when I’m in a Rails 3 app to use r s; I want ss to just work in every project. Unfortunately, you cannot use a Bash alias to solve this problem; you can however use a Bash function! The following is a drop in replacement for the old alias ss=... stuff in your Bash configuration file:

function ss {
  if [ -e script/rails ]; then
    script/rails server $@
  else
    script/server $@
  fi
}
function sc {
  if [ -e script/rails ]; then
    script/rails console $@
  else
    script/console $@
  fi
}
function sg {
  if [ -e script/rails ]; then
    script/rails generate $@
  else
    script/generate $@
  fi
}

They work by checking for the existence of a script/rails file, which is new to Rails 3; if the file exists use it, otherwise fall back to using the Rails 2 version of the command; any arguments given to the function are passed along to the script, which is the $@ bit above.

I’ve contributed these changes to the Terminal project by Pigment, which includes similar shortcuts for many other common tasks.

Update:

A nice refactoring, courtesy of Xavier Noria:

function rails_command {
  local cmd=$1
  shift
  if [ -e script/rails ]; then
    script/rails $cmd "$@"
  else
    script/$cmd "$@"
  fi
}
function ss {
  rails_command "server" "$@"
}
function sc {
  rails_command "console" "$@"
}
function sg {
  rails_command "generate" "$@"
}
function sr {
  rails_command "runner" "$@"
}