Moving from rbenv to chruby and direnv

2014/02/27

I was a happy user of rbenv. It does have some drawback such as having to rbenv rehash everytime after installing new gems or having to manually manage binstubs.But all of them are trivial and can be solved with rbenv's plugins like rbenv-binstubs , rbenv-rehash. But I wanted to try something new, something minimal and so I moved to chruby

Install chruby is pretty easy with homebrew (You are using homebrew, right?):

$ brew install chruby

After that, add the following line to your ~/.zshrc or ~/.bashrc

source /usr/local/share/chruby/chruby.sh

But as the name say chruby main function is only to change ruby :D. To install ruby you must either install ruby-install or ruby-build.

In case, you are already ruby-build (inevitably, if you are using rbenv), you can just use you old ruby installation folder by adding it to the RUBIES variable:

source /usr/local/share/chruby/chruby.sh

RUBIES+=(~/.rbenv/versions/*)

After that, continuing to use ruby-build to manage your ruby installation

In my case, I moved to ruby-install. Install it in just one command line:

$ brew install ruby-install

After that, install the latest and greatest Ruby:

$ ruby-install ruby 2.1.1

To make a ruby version default, simply just call chruby after it was initialized in your ~/.zshrc or ~/.bashrc

...
chruby ruby-2.1.1

If you want to define a specific ruby version for your project and enable auto-switching to that version when cd to your project folder (well, you should), add a .ruby-version file to the root of the folder:

# ./.ruby-version
ruby-2.1.1

And enable the auto-switch function of chruby in your ~/.bashrc or ~/.zshrc file:

source /usr/local/share/chruby/chruby.sh
source /usr/local/share/chruby/auto.sh

Now, you have a working chruby setup. But in your Rails project, you still have to type $ bin/'your-god-knows-gem-command' each time to use your generated gem binstubs. For some people, it's ok, but not for me :D. Previously, when using rbenv, it can be solved with the plugin rbenv-binstubs. With chruby, we will use direnv to eliminate this problem once and for all. Install it with brew:

$ brew install direnv

To add the bin folder of your project to the PATH, create a .envrc with the following line in the root of your project folder:

export PATH=$PWD/bin:$PATH

After that, allow direnv to modify your PATH in this folder

$ cd 'your-project-folder'
$ direnv allow
direnv: loading .envrc
direnv: export ~PATH

From now on, in your project folder, forget the additional bundle exec or bin/ and just type your favorite command.

With chruby and direnv properly setup (you should if you followed my instructions), now we are have a combo of lightweight but effective weapons to adventure with any kind of Ruby project. I wish you all the best :D