Use a Bash function to alias the rake command to Spring binstubs or "bundle exec" fallback

Updated . Posted . Visible to the public.

There are different ways to run rake:

  • On Rails 4.1+ projects, you have Spring and its binstubs which dramatically improve boot-up time for Rake and similar. You need to run bin/rake to use them.
  • On older projects, you want to run "bundle exec rake" to avoid those ugly "already activated rake x.y.z" errors that hit you when different rake versions are installed for your current Ruby.

Here is a solution that gives you a plain rake command which uses a binstubbed bin/rake if available and falls back to bundle exec rake if necessary.

Try it

To see if it works for you, run the following in your bash terminal.

rake() { if [ -f bin/rake ]; then bin/rake "$@"; else bundle exec rake "$@"; fi }

Now, your rake command in the terminal will point to that function:

$ type rake
rake is a function
rake ()
...

Next, try running rake routes on a Rails 4.1+ project -- the 2nd time should be significantly faster. On older projects you should always get your bundled rake.

Persist it

To always enable that short-hand function for terminal sessions, put it into your ~/.bashrc file.

New terminals will know about your custom rake() function.
In existing terminal sessions, reload your bash config:

source ~/.bashrc

Double-check with a type rake just to be sure.

Yaaaay. No more clumsy rake calls!

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2014-09-23 14:30)