Vinicius Rocha

Setup Rails using chruby and ruby-install

I decided to document how I managed to setup Ruby and Rails on my macOS using chruby and ruby-install. Both of them are very light tools written by Hal Brodigan. I'm quite sure that a similar approach could be used on Linux or WSL.

Setup

To install everything, I used Homebrew. As the time of writing this post, this is how we can get it.

$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

With brew installed, we can now get chruby and ruby-install.

$ brew install chruby
$ brew install ruby-install

In order for chruby to work properly, we have to add the following lines to ~/.zshrc file.

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

Using ruby-install

In short, ruby-install is an easy way to install many different flavors of Ruby that are out there: Ruby, JRuby, Rubinius, TruffleRuby (native / GraalVM), or mruby. To get the current stable version of the original Ruby distribution (MRI), just run the following command.

$ ruby-install ruby

And to install a specific version:

$ ruby-install ruby 2.7.5

We might need to run source ~/.zshrc in order to get it visible to chruby without having to restart the terminal session. For move information and other options, refer to the repo README.md file.

Using chruby

Now that we have different versions of Ruby installed, here is where the magic lives! chruby is a very simple and yet powerful tool, written with only about 100 lines of code and, it is capable of automatically switching between Ruby versions depending on the folder that we are at.

To list the installed versions, just run:

$ chruby
   ruby-2.7.5
 * ruby-3.0.3

Note that the current version of Ruby has a * next to it. To switch to a different version, just run:

$ chruby ruby-2.7.5

Be aware that chruby will NOT list the version that comes with macOS. To switch to it, we can run:

$ chruby system

Switching automatically

If we enter a folder that contains a file named .ruby-version, chruby will automatically switch our current version to the one specified inside that file. If we want to change the default version, we can add it to our home directory, like so.

$ echo "ruby-3.0.3" > ~/.ruby-version

Installing Rails

Rails has its own dependencies, so we need to make sure that we have both Node.js and Yarn installed. We can do that also using brew.

$ brew install node
$ brew install yarn

Now, all we need to do is install Rails via RubyGems.

$ gem install rails

If after installing Rails you don't see it in the PATH (command not found), try running source ~/.zshrc once more to update your environment.

Note 1: since the gem is per Ruby installation, it will only be available for the Ruby version that you had selected at that time.