Developing with Bundler
Bundler is a popular Ruby tool, which I have not paid much attention to before. What is it for? And how (or should) I use it?
The main point to remember is that Bundler exists to help developers, not users. In particular, it helps teams of developers use a consistent set of libraries when working on a single project.
Enforcing Dependency Versions
The idea is to enforce, for the developer, a known set of dependency versions,
so different developers can work from the same set of code. This is controlled
using the Gemfile, which stores references to dependent libraries. To start a
project with a single dependency with a known version:
$ bundle init $ bundle add confusion_matrix -v 1.1.0 $ more Gemfile # frozen_string_literal: true source "https://rubygems.org" # gem "rails" gem "confusion_matrix", "= 1.1.0"
We can test the version of a library being used with this simple program:
$ more hello.rb require "confusion_matrix" puts Gem.loaded_specs()["confusion_matrix"]
The last line displays information about the loaded library. When run directly from Ruby, our script picks up the library version currently installed in the global gem list, in this case 1.1.1:
$ ruby hello.rb <Gem::Specification name=confusion_matrix version=1.1.1>
To ensure we use the version specified in the Gemfile, call the script through bundler:
$ bundle exec ruby hello.rb <Bundler::StubSpecification name=confusion_matrix version=1.1.0 platform=ruby>
Controlling Dependencies
Although we can separately list dependencies in the Gemfile, it is considered
better practice to rely on the .gemspec file, e.g. for chess_data:
s.add_dependency 'word_wrap', '~> 1.0'
s.add_development_dependency 'minitest', '~> 6.0'
s.add_development_dependency "rake", "~> 13.0"
We create a file called Gemfile for bundler to use, which reads all the dependencies from
the .gemspec file:
source "https://rubygems.org"
gemspec
There is one caveat to this: if some gems come from a different source, put
them before the gemspec call:
source "https://rubygems.org"
source "https://codeberg.org/api/packages/peterlane/rubygems" do
gem "plane_pdf", "0.1.0"
end
gemspec
Finally, generate the Gemfile.lock file by calling bundle install: this file records
the exact versions of libraries which you are using.
Both the Gemfile and Gemfile.lock files should be included with the source code
for use by other developers - i.e. commit both files to your git repository.
The same set of dependencies can be downloaded using bundle install with the
Gemfile.lock file.
During development, use:
$ bundle exec rake test
which ensures the locked dependencies are used to run the test tasks.