Programming languages · Intermediate · 22 min
Create a Ruby gem with Bundler
By Padding · Updated 18 Nov 2026
Debian (ruby:4.0-slim) · Ruby 4.0.10 · Bundler 4.0.20
You will scaffold a small currency-formatting gem with bundle gem, fill in its gemspec and Gemfile, test it with Minitest 6, check it with Standard, then build the .gem file, install it and use it from a separate script and another project.
On this page
A gem is Ruby's unit of sharing: a .gem file holding your code, a version number and a list of the other gems it needs. RubyGems installs gems. Bundler, which ships with Ruby, decides which versions of them a project uses and records that choice. Both read files you write, and the most common confusion when you first make a gem is which file does what. This tutorial settles that by building one.
You will make cash_label, a small library that turns an amount and a currency code into a label such as ₦1,234.50 or KSh 2,500,000.00. It uses BigDecimal so that rounding is exact, which makes bigdecimal a real runtime dependency. You will test it with Minitest, check its style with Standard, build the .gem file, install it and call it from code that lives outside the gem. Publishing to RubyGems.org is described at the end, but not done, because a published version is public and cannot be replaced.
Every command runs in a terminal on Ubuntu or macOS. The demo lives in ~/gem-demo, so nothing you already have is touched.
Step 1 · Install the build tools
Some gems include C code that is compiled when they are installed. Standard, the style checker you will use, depends on RuboCop, which needs the json, racc and prism gems, and they all compile. Minitest 6 needs prism too. So you need a C compiler, make and the YAML headers (for the psych gem that irb pulls in), plus Git, which bundle gem uses.
On Ubuntu:
sudo apt update
sudo apt install -y git build-essential libyaml-devOn macOS, install Apple's command line tools and libyaml with Homebrew:
xcode-select --install
brew install libyamlThen check Ruby, Bundler and Git:
ruby --version
bundle --version
git --version
git config user.nameCheck it worked
ruby --version starts with ruby 4.0, bundle --version prints a 4.x version such as 4.0.20, and the last line is your own name. If the name is empty, set it with git config --global user.name "Your Name" and do the same for user.email: Bundler copies both into the files it generates.
Step 2 · Generate the gem skeleton
bundle gem writes a complete starting project. Without options it asks a series of questions (test framework, CI, licence, linter), so pass the answers as flags:
mkdir -p ~/gem-demo
cd ~/gem-demo
bundle gem cash_label --test=minitest --linter=standard --mit --changelog --no-coc --no-ci --no-bundle
cd cash_label
find . -path ./.git -prune -o -type f -print | sortThe flags choose Minitest for tests, Standard for style, the MIT licence and a changelog, and skip the code of conduct, CI configuration and the automatic bundle install (you will run it yourself once the files are right). Bundler saves your test framework and linter choices to its global config, so the next bundle gem uses them without asking.
The gem name sets everything else. cash_label becomes the module CashLabel, the main file lib/cash_label.rb, and the version constant in lib/cash_label/version.rb. Use lowercase letters, digits and underscores, and treat a hyphen as a namespace separator: cash-label would mean Cash::Label. Bundler also ran git init in the new folder.
Check it worked
The output ends with Gem 'cash_label' was successfully created. and the file list includes cash_label.gemspec, Gemfile, Rakefile, lib/cash_label.rb, lib/cash_label/version.rb, sig/cash_label.rbs, test/test_helper.rb and test/test_cash_label.rb, along with README.md, LICENSE.txt, CHANGELOG.md, .standard.yml and the helper scripts in bin/.
Step 3 · Fill in the gemspec and declare a dependency
The gemspec is the gem's own description. It is what RubyGems reads when someone installs your gem, so it says what the gem is called, which version it is, which files ship and which other gems it needs at run time. Look at the generated one first:
cat cash_label.gemspecThree things in it need your attention:
summary,description,homepageandallowed_push_hostholdTODOtext. RubyGems refuses a gemspec whose summary starts withTODOand whose URLs are not URLs, and Bundler checks the gemspec before it installs anything, so nothing works until they are filled in.allowed_push_hostlimits wheregem pushmay send the gem. It is there for private gem servers. For a gem meant for RubyGems.org you can remove it.spec.filesasks Git for the list of files (git ls-files). That means a new file is left out of the gem until yougit addit, a common surprise. The version below lists the shipped files withDir.globinstead, so what ships is written down in the gemspec.
Replace the file with this version. Put your own name, email and homepage in place of the example values:
cat > cash_label.gemspec <<'RUBY'
# frozen_string_literal: true
require_relative "lib/cash_label/version"
Gem::Specification.new do |spec|
spec.name = "cash_label"
spec.version = CashLabel::VERSION
spec.authors = ["Your Name"]
spec.email = ["you@example.com"]
spec.summary = "Format amounts of money as short, readable labels."
spec.description = "CashLabel turns an amount and an ISO 4217 currency code into a label such as $1,234.50, rounding with BigDecimal so the result is exact."
spec.homepage = "https://example.com/cash_label"
spec.license = "MIT"
spec.required_ruby_version = ">= 3.2.0"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["changelog_uri"] = "https://example.com/cash_label/CHANGELOG.md"
spec.metadata["rubygems_mfa_required"] = "true"
spec.files = Dir.glob(["lib/**/*.rb", "sig/**/*.rbs", "LICENSE.txt", "README.md", "CHANGELOG.md"], base: __dir__)
spec.require_paths = ["lib"]
spec.add_dependency "bigdecimal", "~> 4.0"
end
RUBYThe last line is the dependency. BigDecimal used to be part of Ruby itself, but since Ruby 3.4 it is a bundled gem: it is installed with Ruby, yet code that runs under Bundler can only load it if a gemspec or Gemfile asks for it. Declaring it here means anyone who installs cash_label gets bigdecimal too. "~> 4.0" allows any 4.x version from 4.0 up, and nothing from 5.0, which could change behaviour.
rubygems_mfa_required is covered in the last step. base: __dir__ makes the file list relative to the gemspec's own folder, so it is the same wherever the gemspec is loaded from.
Check it worked
Ask RubyGems to load the gemspec and print what it found:
ruby -e 'spec = Gem::Specification.load("cash_label.gemspec"); puts spec.full_name; puts spec.files; puts spec.runtime_dependencies'The output starts with cash_label-0.1.0, lists the files under lib/ and sig/ along with the README, licence and changelog, and ends with bigdecimal (~> 4.0). No test/ file appears: tests are for you, not for the people who install the gem.
Step 4 · Set up the Gemfile and install
The Gemfile is for working on the gem, not for using it. It lists the tools you need while developing (Rake, Minitest, Standard, irb for bin/console) and, through the gemspec line, pulls in the gemspec's runtime dependencies too. Look at the generated one:
cat GemfileIt pins Minitest to ~> 5.16 and Standard to ~> 1.3. Those are the generator's safe minimums, and ~> 5.16 would hold you on Minitest 5. Replace the file so it uses the current releases:
cat > Gemfile <<'RUBY'
# frozen_string_literal: true
source "https://rubygems.org"
# Runtime dependencies come from cash_label.gemspec.
gemspec
gem "irb"
gem "rake", "~> 13.4"
gem "minitest", "~> 6.1"
gem "standard", "~> 1.57"
RUBY
bundle installThe install downloads and compiles the gems, which takes a minute or two the first time. On prepaid mobile data, run it once on Wi-Fi: later projects reuse the gems already installed.
Bundler writes the exact versions it chose to Gemfile.lock. Read the top of it:
sed -n '1,12p' Gemfile.lockThe PATH section is your own gem, found at . (this folder), with the dependency from its gemspec underneath. The GEM section lists every gem fetched from RubyGems.org with its exact version, including the ones Standard and Minitest brought with them. Further down, DEPENDENCIES repeats what the Gemfile asked for, and BUNDLED WITH records the Bundler version.
Commit Gemfile.lock to Git along with the rest, so everyone working on the gem gets the same tool versions. People who install your gem never see it: RubyGems resolves your gem's dependencies from the gemspec alone, which is why the gemspec uses a range and the lockfile holds exact versions.
Check it worked
bundle install ends with Bundle complete!. In the lockfile, the PATH section shows cash_label (0.1.0) followed by bigdecimal (~> 4.0), and grep minitest Gemfile.lock shows a minitest (6.1.0) line or a later 6.x.
Step 5 · Write the formatter
Replace lib/cash_label.rb with the library code. It keeps a small table of currencies, converts the amount to BigDecimal through a string (so a float such as 0.1 + 0.2 becomes the number you meant, not its binary approximation), rounds half away from zero to the currency's decimal places, then groups the thousands:
cat > lib/cash_label.rb <<'RUBY'
# frozen_string_literal: true
require "bigdecimal"
require_relative "cash_label/version"
module CashLabel
class Error < StandardError; end
class UnknownCurrency < Error; end
CURRENCIES = {
"NGN" => {symbol: "₦", decimals: 2},
"KES" => {symbol: "KSh ", decimals: 2},
"GHS" => {symbol: "GH₵", decimals: 2},
"ZAR" => {symbol: "R ", decimals: 2},
"USD" => {symbol: "$", decimals: 2},
"EUR" => {symbol: "€", decimals: 2},
"GBP" => {symbol: "£", decimals: 2},
"JPY" => {symbol: "¥", decimals: 0}
}.freeze
def self.format(amount, currency)
code = currency.to_s.upcase
info = CURRENCIES.fetch(code) { raise UnknownCurrency, "unknown currency: #{code}" }
value = BigDecimal(amount.to_s).round(info[:decimals], BigDecimal::ROUND_HALF_UP)
whole, fraction = value.abs.to_s("F").split(".")
grouped = whole.reverse.scan(/\d{1,3}/).join(",").reverse
number = info[:decimals].zero? ? grouped : "#{grouped}.#{fraction.ljust(info[:decimals], "0")}"
sign = value.negative? ? "-" : ""
"#{sign}#{info[:symbol]}#{number}"
end
end
RUBYCashLabel::Error is the base class callers can rescue for anything the gem raises, a convention the generated file already set up. BigDecimal#to_s("F") prints plain decimal notation such as 1234.5, which is split into the whole part and the fraction.
The currency table is deliberately small. A full library would load the ISO 4217 list and handle locale rules, such as which separator a country uses. That is a reason to depend on another gem, and you now know where that dependency would go.
Check it worked
Run the code through Bundler, which puts the gemspec's dependencies on the load path:
bundle exec ruby -Ilib -e 'require "cash_label"; puts CashLabel.format(1234.5, "NGN")'It prints ₦1,234.50. If you see cannot load such file -- bigdecimal, the add_dependency line is missing from the gemspec.
Step 6 · Test it with Minitest
The generated test file contains a test that always fails (assert false), a reminder to write real ones. Replace it:
cat > test/test_cash_label.rb <<'RUBY'
# frozen_string_literal: true
require "test_helper"
class TestCashLabel < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::CashLabel::VERSION
end
def test_groups_thousands_and_pads_decimals
assert_equal "₦1,234.50", CashLabel.format(1234.5, "NGN")
end
def test_accepts_strings_and_lowercase_codes
assert_equal "KSh 2,500,000.00", CashLabel.format("2500000", "kes")
end
def test_rounds_half_up_to_the_currency_decimals
assert_equal "$0.30", CashLabel.format(0.1 + 0.2, "USD")
assert_equal "-$12.35", CashLabel.format("-12.345", "USD")
end
def test_currency_without_minor_units
assert_equal "¥2,000", CashLabel.format(1999.5, "JPY")
end
def test_unknown_currency_raises
error = assert_raises(CashLabel::UnknownCurrency) { CashLabel.format(10, "XYZ") }
assert_equal "unknown currency: XYZ", error.message
end
end
RUBY
bundle exec rake testEach method whose name starts with test_ is one test. test/test_helper.rb, also generated, adds lib to the load path, loads the gem and requires minitest/autorun. The Rakefile creates the test task with Minitest::TestTask, which runs every test/**/test_*.rb file.
If you move from Minitest 5, two Minitest 6 changes are worth knowing. assert_equal nil, value is now an error, so use assert_nil value. And mocks (Minitest::Mock) moved out into a separate gem, minitest-mock, which you add to the Gemfile if you use them.
Check it worked
The output ends with a summary line like 6 runs, 8 assertions, 0 failures, 0 errors, 0 skips. To see a failure, change "$0.30" to "$0.3" in the test, run bundle exec rake test again, read the Expected and Actual lines it prints, then change it back.
Step 7 · Check the style with Standard
Standard is RuboCop with a fixed set of rules, so there is nothing to configure and nothing to argue about. The generated Rakefile already loads its tasks. Check every Ruby file in the project, including the gemspec and the Gemfile:
bundle exec rake standardWhen Standard reports problems, most can be fixed for you. bundle exec rake standard:fix rewrites the files (for example, single quotes to double quotes, or spacing inside hashes) and lists anything it could not fix. Commit or save your work before you run it, so you can review its changes.
The Rakefile's default task runs the tests and then Standard, which makes rake on its own the check to run before every commit:
bundle exec rakeCheck it worked
bundle exec rake standard prints nothing and exits without an error. bundle exec rake prints the test summary with 0 failures, 0 errors, then nothing more from Standard. Run bundle exec rake -T to see the other tasks the gem gets from Bundler, such as build, install and release.
Step 8 · Build the gem, install it and use it
Build the .gem file from the gemspec, then list what is inside it:
gem build cash_label.gemspec
gem specification cash_label-0.1.0.gem filesgem build prints Successfully built RubyGem with the name, version and file name cash_label-0.1.0.gem. Install that file as if you had downloaded it:
gem install ./cash_label-0.1.0.gem --no-document
gem list cash_labelThe gem is now installed like any other. Use it from a script outside the project, where there is no Gemfile and no -Ilib, so Ruby finds it through RubyGems alone:
cd ~/gem-demo
cat > price_list.rb <<'RUBY'
require "cash_label"
prices = [[1500, "NGN"], [349.99, "KES"], [12.5, "GHS"], [4999, "JPY"]]
prices.each { |amount, code| puts CashLabel.format(amount, code) }
RUBY
ruby price_list.rbA project that uses your gem lists it in its own Gemfile. While you work on both at once, point the Gemfile at the gem's folder with path::
mkdir -p ~/gem-demo/shop
cd ~/gem-demo/shop
cat > Gemfile <<'RUBY'
source "https://rubygems.org"
gem "cash_label", path: "../cash_label"
RUBY
cat > receipt.rb <<'RUBY'
require "cash_label"
puts "Total: #{CashLabel.format("2750.5", "ZAR")}"
RUBY
bundle install
bundle exec ruby receipt.rbBundler reads ../cash_label/cash_label.gemspec, installs the gem's dependencies and uses your working copy, so a change in the gem shows up here without rebuilding. Once the gem is published, the line becomes gem "cash_label", "~> 0.1".
This is the whole split between the two files:
- The gemspec describes the gem to everyone who installs it: name, version, files, and runtime dependencies as ranges. It ships inside the
.gemfile. - The Gemfile describes a project's working environment: the gems it uses and the development tools around them. A gem's Gemfile adds tools on top of its gemspec; an application's Gemfile lists the gems it uses, including yours.
- Gemfile.lock records the exact versions Bundler chose for one project. It is never shipped in a gem.
Check it worked
gem list cash_label shows cash_label (0.1.0). ruby price_list.rb prints four lines: ₦1,500.00, KSh 349.99, GH₵12.50 and ¥4,999. bundle exec ruby receipt.rb prints Total: R 2,750.50.
Step 9 · Publish when you are ready, then clean up
Do not publish cash_label itself: the name is a demo and another person may already own it. For a gem of your own, the steps are below. They need an account on RubyGems.org, and they are listed here for reference only.
Before you push, know three things:
- Turn on multi-factor authentication (MFA) in your RubyGems.org account settings, with a security key (WebAuthn) or an authenticator app. Save the recovery codes it shows once. With the "UI and API" level, signing in, pushing and changing owners all ask for a code.
rubygems_mfa_required, set in the gemspec above, makes RubyGems.org require MFA from every owner of the gem for pushes and other changes. It protects users if a co-owner's password leaks.- A version number is used once. You can remove a broken release from the index with
gem yank cash_label -v 0.1.0, but you cannot upload a different file as 0.1.0 again. Bumplib/cash_label/version.rband add aCHANGELOG.mdentry for every release.
Then sign in, which stores an API key in your home folder, and push the file:
gem signin
gem push cash_label-0.1.0.gemFrom the gem's folder, bundle exec rake release does the same work and more: it builds the gem, creates and pushes a v0.1.0 Git tag, and pushes the gem. It needs a clean Git working tree and a remote to push to. For releases from CI, RubyGems.org supports trusted publishing from GitHub Actions, which uses short-lived credentials instead of a stored API key. If you do create an API key, give it only the scopes it needs, such as push rights for one gem.
When you have finished with the demo, uninstall the gem and remove the folder:
gem uninstall cash_label -v 0.1.0
cd ~
rm -rf ~/gem-demoThe development gems (Standard, RuboCop, Minitest and their dependencies) stay installed and are shared with your other projects. bundle gem also saved Minitest and Standard as your defaults for new gems. To see them, run bundle config. To drop them, run bundle config unset --global gem.test and bundle config unset --global gem.linter.
Check it worked
gem list -i cash_label prints false, and ls ~/gem-demo reports that the folder does not exist.
Next steps
- Write the Ruby that goes inside a gem the idiomatic way: use blocks, procs and Enumerable in Ruby.
- Compare the same ideas in PHP, where composer.json plays both roles: manage PHP dependencies and autoloading with Composer.
- See how Python splits a package description from a lockfile: package a Python project with uv and pyproject.toml.
- Back to basics, or show a friend where to start: Hello World in Ruby.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials