Some useful Bash shortcuts for Ruby on Rails commands

Read an updated article on my Rails shortcuts: Bash shortcuts to run Rails commands through Spring, Bundler, or ye olde scripts

Like any developer, I spend a lot of time in the terminal typing out commands. Anything I can do to cut down on keystrokes is a daily win, which is why I’ve got over 50 bash alias entries.

I frequently have to work on a several different Rails projects at a time, ranging in versions from 2.3 – 4.0. Hammering out commands for console, server or generate can get pretty tedious by the end of the day, so I came up with a couple shortcuts that I’m particularly fond of:

# RUBY / RUBY ON RAILS COMMANDS
alias rails_mv="rails -v | sed 's/Rails \([0-9]\).*/\1/g'"
alias bexec='bundle exec'
alias brake='bundle exec rake'
function cons () {
  if [ `rails_mv` -lt 3 ]; then
    ./script/console "$@"
  else
    bexec rails c "$@"
  fi
}
function gen () {
  if [ `rails_mv` -lt 3 ]; then
    ./script/generate "$@"
  else
    bexec rails g "$@"
  fi
}
function srv () {
  if [ `rails_mv` -lt 3 ]; then
    ./script/server "$@"
  else
    bexec rails s "$@"
  fi
}
alias sandbox='cons --sandbox'

What I like most about the cons, srv and gen commands is that they eliminate the mental overhead of context switching when going from the old 1.x and 2.x projects where each command is a separate bin file versus the newer 3.x+ project where they are just arguments to the rails command – It’s the same alias for every project.

He hoped and prayed that there wasn’t an afterlife. Then he realized there was a contradiction involved here and merely hoped that there wasn’t an afterlife.

— Douglas Adams, Life, the Universe and Everything