What Does Gemfile.lock File Use for in Ruby on Rails?
You have noticed a file called Gemfile.lock in your Ruby on Rails application and have wondered what is it, how it works. The file may have even given you trouble when you attempted to push changes to source control. In this article I will discuss what exactly this Gemfile.lock file is and how it helps your Ruby on Rails application.
Gemfile.lock
If you actually opened the Gemfile.lock file you probably saw a bunch of text as below:
The Gemfile.lock file stores a complete snapshot of every version of every gem your Ruby on Rails application uses. The reason for this is simple. Let’s say you are using Rails 4.1.6 and Rails 5.0 comes out. You don’t want this new version to be pushed to your application during the next update. Why? You developed your application using the old version, and the new version may not be compatible with your code. That is why it is also important to check your Gemfile.lock into source control with the rest of your application.
The Gemfile.lock file not only stores exact version information, but bundler USES that version information to rebuild the snapshot on production. If you take a look at your Gemfile (not Gemfile.lock) for example you will see the following line:
1
gem'coffee-rails','~> 4.0.0'
Bundler knows that you used version 4.0.1 during development. When this file is pushed to production and you run a bundle install –deployment, bundler will recreate a snapshot of all of the gems that you were using on your development machine.
When does this file get updated? Any time you add a new gem to your gemfile (and run a bundle install) or type bundle update [gem name] your Gemfile.lock will get updated. If you attempt to update the version of a Gem in your Gemfile, bundler will warn you to do a bundle update the next time you try to run a bundle install.
In this case, you would be unable to proceed until you run bundle update coffee-rails, which would then update your Gemfile.lock to include the new version of coffee-rails. This is also why it’s disastrous to run a bundle update without specifying a gem. Bundle update rebuilds the entire Gemfile.lock file from scratch, blowing away all of the old versions and replacing them with the latest ones allowed by the Gemfile.
So far so good, the Gemfile.lock file is designed to save headache and frustration when deploying your application both across development machines as well as to production. It’s always a good idea to make sure that you check this file into source control and be aware of how it works. That’s it! See ya!