Gemfile and Bundler
In lesson 50 you installed gems one at a time. A real project soon needs a dozen – and gems need gems of their own: Sinatra brings Rack, Mustermann, Tilt and a few more. Which versions go together? And how do your colleague's laptop and the server get exactly the same ones? That is the job of Bundler, which has come with Ruby since 2.6. You write what you want into a file called Gemfile; Bundler finds versions that fit together, installs them and notes down what it picked in Gemfile.lock.
Bundler itself cannot run on this page: it needs all of RubyGems, and the Ruby in your browser carries only a slimmed-down part of it. So this lesson takes Bundler's ideas apart and builds each one in a few lines of Ruby that do run here – with the real Gem::Version and Gem::Requirement, the very classes Bundler compares versions with. First: a Gemfile is not a settings file. It is Ruby.
gemfile = <<~GEMFILE
source "https://rubygems.org"
gem "sinatra", "~> 4.1"
gem "rack", ">= 3.0", "< 3.2"
gem "chunky_png"
group :test do
gem "minitest", "~> 5.25"
end
GEMFILE
# A tiny Gemfile reader: every line of the Gemfile becomes a method call
class GemfileReader
attr_reader :sources, :gems
def initialize
@sources = []
@gems = []
@groups = [:default]
end
def source(url)
@sources << url
end
def gem(name, *requirements)
@gems << { name: name, requirements: requirements, groups: @groups }
end
def group(*names)
outer = @groups
@groups = names
yield
ensure
@groups = outer
end
end
reader = GemfileReader.new
reader.instance_eval(gemfile)
reader.gems.each { |g| p g }
reader.sourcessource, gem and group look like keywords, but they are ordinary method calls without parentheses. instance_eval runs the Gemfile's text with self set to reader, so every gem "…" lands in reader.gem, and group :test do … end is a method that takes a block. Bundler reads your Gemfile the same way: its class Bundler::Dsl has the methods source, gem, group and a few more (ruby, gemspec, git, path) and evaluates the file with instance_eval. A little language made of method calls like this is called a DSL (domain-specific language). The group marks gems you only need for the tests – a server can leave them out.
Versions are not strings
After a gem's name come its requirements: "~> 4.1", ">= 3.0". Checking one means comparing versions – and strings are bad at that:
require "rubygems/requirement"
# Compared as strings: character by character
p "1.10" > "1.9"
p Gem::Version.new("1.10") > Gem::Version.new("1.9")
versions = ["3.1.8", "2.2.9", "3.10.0", "3.2.7", "3.0.0"]
p versions.max
p versions.max_by { |v| Gem::Version.new(v) }
versions.sort_by { |v| Gem::Version.new(v) }Strings are compared character by character, and "1" comes before "9" – so "1.10" loses to "1.9", and max crowns 3.2.7 instead of 3.10.0. Gem::Version splits at the dots and compares number by number: 10 is more than 9. It also knows pre-releases: "4.0.0.beta1" comes before "4.0.0".
Most gems number their versions the semantic versioning way, MAJOR.MINOR.PATCH: a new patch fixes bugs, a new minor adds features, and only a new major may break code that uses the gem. The requirement operators build on that:
versions = ["2.2.9", "3.0.0", "3.1.8", "3.2.7", "4.0.0"]
["= 3.1.8", ">= 3.1", "< 3", "~> 3.1", "~> 3.1.0"].each do |text|
requirement = Gem::Requirement.new(text)
fitting = versions.select { |v| requirement.satisfied_by?(Gem::Version.new(v)) }
puts "#{text.ljust(9)} #{fitting.join(" ")}"
end
# Several requirements at once: all of them must hold
both = Gem::Requirement.new(">= 3.0", "< 3.2")
versions.select { |v| both.satisfied_by?(Gem::Version.new(v)) }= wants exactly that version; >= and < mean what they say. The most useful one is ~>, the pessimistic operator: ~> 3.1 means "3.1 or newer, but below 4.0" – the last number you write may grow, the ones before it stay put. So ~> 3.1.0 allows only 3.1.x: bug fixes yes, new features no. Either way you get updates and are safe from the next major. Several requirements on one gem must all hold, as in gem "rack", ">= 3.0", "< 3.2".
Gemfile.lock: the same versions everywhere
The Gemfile says what would fit, not what you got. ~> 4.1 means Sinatra 4.2.2 today and perhaps 4.3.0 next month. So bundle install writes every gem with its exact version into Gemfile.lock – the gems your gems pull in too. The next bundle install, on your computer, your colleague's or the server, installs exactly those versions again until you ask for an update. That is why the lock file goes into git next to the Gemfile. Here is the real lock file Bundler 4.0.18 wrote for the Gemfile above (without its CHECKSUMS section, a SHA-256 checksum per gem):
lockfile = <<~LOCK
GEM
remote: https://rubygems.org/
specs:
base64 (0.3.0)
chunky_png (1.4.0)
logger (1.7.0)
minitest (5.27.0)
mustermann (3.1.1)
rack (3.1.24)
rack-protection (4.2.2)
base64 (>= 0.1.0)
logger (>= 1.6.0)
rack (>= 3.0.0, < 4)
rack-session (2.1.2)
base64 (>= 0.1.0)
rack (>= 3.0.0)
sinatra (4.2.2)
logger (>= 1.6.0)
mustermann (~> 3.0)
rack (>= 3.0.0, < 4)
rack-protection (= 4.2.2)
rack-session (>= 2.0.0, < 3)
tilt (~> 2.0)
tilt (2.9.0)
PLATFORMS
ruby
x86_64-linux
DEPENDENCIES
chunky_png
minitest (~> 5.25)
rack (>= 3.0, < 3.2)
sinatra (~> 4.1)
BUNDLED WITH
4.0.18
LOCK
# Four spaces in: a gem and the exact version Bundler picked.
# Six spaces: what that gem needs itself.
locked = {}
lockfile.each_line do |line|
locked[$1] = $2 if line =~ /\A {4}(\S+) \((.+)\)$/
end
lockedFour gems in the Gemfile became ten in the lock: Sinatra pulled in the other six. Under DEPENDENCIES the lock file repeats your requirements; under specs stands what Bundler decided. Those versions must fit the requirements – checked with the reader from the first cell:
reader.gems.all? do |g|
requirement = Gem::Requirement.new(*g[:requirements])
version = locked[g[:name]]
fits = requirement.satisfied_by?(Gem::Version.new(version))
puts "#{g[:name]} #{version}, wanted #{requirement}: #{fits ? "ok" : "DOES NOT FIT"}"
fits
endThat check is the first thing Bundler does on every start: does the lock still fit the Gemfile? If you have changed the Gemfile, it resolves again – and that is the hard part. For every gem it has to find a version that satisfies all requirements on it, from your Gemfile and from the dependencies of every other gem, and when two of them disagree it backs off and tries an older version somewhere. Bundler uses the PubGrub algorithm for that. In the task you write its core, one gem at a time.
Bundler comes with Ruby. In a project folder:
bundle init– creates an empty Gemfilebundle add sinatra– addsgem "sinatra", "~> 4.2"and installs itbundle install– installs whatGemfile.locksays (resolves first if needed)bundle exec ruby app.rb– runs with exactly the locked versionsbundle update rack– moves rack to the newest version that fitsbundle outdated– lists gems that have newer versionsbundle config set --local without test– this computer leaves out group:test
Why bundle exec? Without it, require "rack" loads the newest rack installed on your computer – maybe 3.2, not the locked 3.1.24. bundle exec, or require "bundler/setup" at the top of a program, puts only the locked versions on the load path. And for a single script without a Gemfile, require "bundler/inline" gives you gemfile do … end right inside the file.
index is what a gem server knows: for every gem name the versions it has, in any order. newest_match(index, name, *requirements) returns the newest version of name, as a string, that satisfies every requirement (no requirements at all: any version) – or nil if none does or the gem is unknown. Then resolve_all(index, wishes) takes a hash like a tiny Gemfile, one requirement or a list of them per gem: { "sinatra" => "~> 4.1", "rack" => [">= 3.0", "< 3.2"] }. It returns a hash of each name and its chosen version – and if a gem has no fitting version, it raises an error whose message names that gem.require "rubygems/requirement"
def newest_match(index, name, *requirements)
# the newest version of name in index that satisfies every requirement,
# as a String - nil if there is none
end
def resolve_all(index, wishes)
# { "rack" => "~> 3.1", ... } => { "rack" => "3.2.7", ... }
# raise an error naming the gem when no version of it fits
end
index = {
"rack" => ["2.2.9", "3.0.0", "3.1.8", "3.2.7"],
"sinatra" => ["3.2.0", "4.0.0", "4.1.1", "4.2.2"],
"tilt" => ["1.4.1", "2.0.9", "2.0.10", "2.0.11"],
}
p newest_match(index, "rack", "~> 3.1") # "3.2.7"
p newest_match(index, "tilt", "~> 2.0") # "2.0.11"
p newest_match(index, "rack", "~> 4.0") # nil
resolve_all(index, { "sinatra" => "~> 4.1", "rack" => [">= 3.0", "< 3.2"] })