Integrating .ruby-version into your Rails Gemfile

Developers often use different versions of Ruby in different Rails projects. We typically manage these versions using solutions such as rbenv or RVM or asdf. These solutions allow a .ruby-version file to specify the current Ruby version to be used in a particular project directory.
However, switching between projects also requires updating the Ruby version specified in the Rails application's Gemfile. This is a duplication of effort that we can avoid for more efficient coding. In this article, we'll discover how to load the .ruby-version file directly into your Rails application's Gemfile.

Requirements

Before proceeding, you must have Bundler version 2.4.2.0 or higher. To upgrade, run the following commands:

gem update --system  # Updates your RubyGems
bundle update --bundler  # Updates Bundler

Typical Usage of .ruby-version and Gemfile

In a typical Rails app, we define the Ruby version separately in the Gemfile and .ruby-version file. Given that the .ruby-version file has 3.1.2:

# .ruby-version
3.1.2

# Gemfile also needs to be updated
ruby "3.1.2"

Maintaining two separate Ruby version declarations can be unproductive and error-prone.

Best practice: Load .ruby-version into Gemfile

A more efficient approach is to point the Gemfile to our .ruby-version file. This way we maintain a single source of truth for our Ruby version, and it will automatically update in our Rails application when we change our .ruby-version file. Modify your Gemfile as shown:

# Gemfile
ruby file: ".ruby-version"

This way, it directly reads the Ruby version from the .ruby-version file in your project directory. If this file shows version 3.1.2, then that's what your Gemfile will load.

Conclusion

Having a single source of truth for your Ruby version helps to avoid inconsistencies and is a more efficient development practice. Integrating the .ruby-version file into your Gemfile eliminates the need to manually synchronize both files. As long as you have Bundler version 2.4.2.0 or higher, it's a small change to your Gemfile that will improve your Rails development.

Happy versioning!