Building and distributing programs
suggest changeRuby is interpreted, so there is no compile step that turns your code into a binary. "Building" a Ruby program means packaging the source files together with a description of their dependencies. "Distributing" means getting that package onto another machine in a form that's easy to run.
There are several ways to do that. Which one fits depends on who runs the program:
| Audience | Approach |
|---|---|
| You or a colleague, one file | a script with a shebang and bundler/inline |
| Ruby developers | a gem with an executable, published to rubygems.org or a private server |
| Your own servers | the source tree plus Gemfile.lock, installed with Bundler (often in a Docker image) |
| End users who don't have Ruby | a self-contained executable (OCRAN, Tebako) |
This article walks through all of them using one small command-line tool. All commands were run with Ruby 4.0, RubyGems/Bundler 4.0 and OCRAN 1.5.
Single-file scripts
For a one-file tool, add a shebang line so it can run directly on Unix-like systems (chmod +x tool.rb, then ./tool.rb). To declare gem dependencies, use bundler/inline, which installs missing gems the first time the script runs:
#!/usr/bin/env ruby
# frozen_string_literal: true
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "rainbow", "~> 3.1"
end
puts Rainbow("ok").green + " running on Ruby #{RUBY_VERSION}"
ok running on Ruby 4.0.7
On Windows, the RubyInstaller associates .rb files with ruby.exe, and ruby tool.rb works everywhere. This is the simplest way to distribute a program, but it only scales to a single file and it requires Ruby on the target machine. See Bundler inline for more.
Structure of a distributable program
Anything bigger than one file should be a gem, even if you never publish it. A gem gives you a standard layout, a version number, declared dependencies, and an executable that RubyGems puts on the PATH.
bundle gem NAME --exe generates a skeleton. Here is a slimmed-down version for a tool called wordfreq that prints the most common words in text:
wordfreq/
exe/wordfreq # the command users run
lib/wordfreq.rb # entry point for `require "wordfreq"`
lib/wordfreq/cli.rb # command-line handling
lib/wordfreq/version.rb # VERSION constant
test/test_wordfreq.rb
Gemfile
Rakefile
wordfreq.gemspec
README.md
LICENSE.txt
The version lives in its own file so the gemspec can load it without loading the whole library:
# lib/wordfreq/version.rb
# frozen_string_literal: true
module Wordfreq
VERSION = "0.1.0"
end
The library code:
# lib/wordfreq.rb
# frozen_string_literal: true
require_relative "wordfreq/version"
require_relative "wordfreq/cli"
module Wordfreq
# Returns the n most common words as [[word, count], ...]
def self.top(text, n = 10)
text.downcase.scan(/[[:alpha:]']+/).tally.sort_by { |word, count| [-count, word] }.first(n)
end
end
Put the command-line logic in a class, not in the executable. The class can be tested, and it returns an exit status instead of calling exit itself:
# lib/wordfreq/cli.rb
# frozen_string_literal: true
require "optparse"
module Wordfreq
class CLI
def self.start(argv = ARGV, out: $stdout)
new.run(argv, out)
end
def run(argv, out)
limit = 5
parser = OptionParser.new do |o|
o.banner = "Usage: wordfreq [options] [FILE...]"
o.on("-n", "--top N", Integer, "show N words (default 5)") { |v| limit = v }
o.on("-v", "--version", "print version") do
out.puts "wordfreq #{VERSION}"
return 0
end
end
files = parser.parse(argv)
text = files.empty? ? $stdin.read : files.map { |f| File.read(f) }.join("\n")
Wordfreq.top(text, limit).each { |word, count| out.puts format("%6d %s", count, word) }
0
rescue OptionParser::ParseError, SystemCallError => e
warn "wordfreq: #{e.message}"
1
end
end
end
The executable stays tiny. It has no .rb extension because users type its name as a command:
#!/usr/bin/env ruby
# frozen_string_literal: true
require "wordfreq"
exit Wordfreq::CLI.start(ARGV)
Notice require "wordfreq", not require_relative "../lib/wordfreq". Once the gem is installed, RubyGems adds the gem's lib directory to the load path, so a plain require works. In development you add lib to the load path yourself:
$ ruby -Ilib exe/wordfreq sample.txt
4 the
3 fox
2 dog
2 quick
1 a
$ ruby -Ilib exe/wordfreq -n 2 < sample.txt
4 the
3 fox
$ ruby -Ilib exe/wordfreq nope.txt; echo "exit=$?"
wordfreq: No such file or directory @ rb_sysopen - nope.txt
exit=1
bundle exec wordfreq (or bundle exec ruby exe/wordfreq) works too, because the Gemfile contains gemspec, and Bundler then puts the gem's lib on the load path and its executables on the PATH.
For more on parsing options see OptionParser and Command Line Apps.
The gemspec
The gemspec says what goes into the package:
# wordfreq.gemspec
# frozen_string_literal: true
require_relative "lib/wordfreq/version"
Gem::Specification.new do |spec|
spec.name = "wordfreq"
spec.version = Wordfreq::VERSION
spec.authors = ["Jane Doe"]
spec.email = ["jane@example.com"]
spec.summary = "Print the most frequent words in text files"
spec.homepage = "https://github.com/janedoe/wordfreq"
spec.license = "MIT"
spec.required_ruby_version = ">= 3.2"
spec.metadata["source_code_uri"] = spec.homepage
spec.metadata["rubygems_mfa_required"] = "true"
spec.files = Dir["lib/**/*.rb", "exe/*", "README.md", "LICENSE.txt"]
spec.bindir = "exe"
spec.executables = ["wordfreq"]
spec.require_paths = ["lib"]
# runtime dependencies go here, e.g.:
# spec.add_dependency "rainbow", "~> 3.1"
end
The fields that matter for distribution:
filesis the exact list of files that end up in the package. Anything missing from it simply isn't there after installation. The skeleton frombundle gemusesgit ls-filesinstead ofDir[], so a file you haven't added to git yet is silently left out. Tests, CI config and the Gemfile normally stay out.bindirandexecutablestell RubyGems which scripts to put on the user'sPATH.bundle gemusesexe/for these and keepsbin/for development scripts likebin/setupandbin/console.required_ruby_versionkeeps users on older Rubies from installing a version that won't work for them. When they rungem install, RubyGems picks the newest release that supports their Ruby.add_dependencydeclares runtime dependencies. Use the pessimistic operator~>with major and minor ("~> 3.1"means>= 3.1, < 4.0). Development-only tools such as rake and minitest belong in theGemfile, not in the gemspec.rubygems_mfa_requiredmakes rubygems.org refuse pushes of this gem from anyone who isn't using multi-factor authentication.
The field-by-field reference is in Gemspec Files.
Building the gem
gem build produces a .gem file:
$ gem build wordfreq.gemspec
Successfully built RubyGem
Name: wordfreq
Version: 0.1.0
File: wordfreq-0.1.0.gem
A .gem is a plain tar archive. Before you publish, look inside to check that the right files made it in:
$ tar -tf wordfreq-0.1.0.gem
metadata.gz
data.tar.gz
checksums.yaml.gz
$ tar -xOf wordfreq-0.1.0.gem data.tar.gz | tar -tzf -
LICENSE.txt
README.md
exe/wordfreq
lib/wordfreq.rb
lib/wordfreq/cli.rb
lib/wordfreq/version.rb
gem specification wordfreq-0.1.0.gem --ruby prints the metadata that was baked in. You'll see s.date = "1980-01-02" there. That's deliberate: RubyGems builds reproducible gems, so building the same source twice gives byte-identical files. Set SOURCE_DATE_EPOCH if you want a real timestamp.
Rake tasks
With require "bundler/gem_tasks" in the Rakefile, you get standard tasks for the whole release cycle:
# Rakefile
# frozen_string_literal: true
require "bundler/gem_tasks"
require "minitest/test_task"
Minitest::TestTask.create
task default: :test
$ bundle exec rake -T
rake build # Build wordfreq-0.1.0.gem into the pkg directory
rake build:checksum # Generate SHA512 checksum of wordfreq-0.1.0.gem into the checksums directory
rake clean # Remove any temporary products
rake clobber # Remove any generated files
rake install # Build and install wordfreq-0.1.0.gem into system gems
rake install:local # Build and install wordfreq-0.1.0.gem into system gems without network access
rake release[remote] # Create tag v0.1.0 and build and push wordfreq-0.1.0.gem to rubygems.org
rake test # Run the test suite
...
$ bundle exec rake build
wordfreq 0.1.0 built to pkg/wordfreq-0.1.0.gem.
rake release refuses to run if the git working tree has uncommitted changes. Otherwise it builds the gem, tags the commit v0.1.0, pushes the commit and the tag, and then runs gem push.
Installing and testing the package locally
Install the .gem file directly. The ./ prefix tells RubyGems it's a local file and not a gem name to look up on rubygems.org:
$ gem install ./wordfreq-0.1.0.gem
Successfully installed wordfreq-0.1.0
Parsing documentation for wordfreq-0.1.0
Installing ri documentation for wordfreq-0.1.0
Done installing documentation for wordfreq after 0 seconds
1 gem installed
$ wordfreq -n 3 sample.txt
4 the
3 fox
2 dog
$ gem contents wordfreq
.../gems/wordfreq-0.1.0/LICENSE.txt
.../gems/wordfreq-0.1.0/README.md
.../gems/wordfreq-0.1.0/exe/wordfreq
.../gems/wordfreq-0.1.0/lib/wordfreq.rb
.../gems/wordfreq-0.1.0/lib/wordfreq/cli.rb
.../gems/wordfreq-0.1.0/lib/wordfreq/version.rb
RubyGems doesn't copy exe/wordfreq onto the PATH as is. It writes a wrapper (a "binstub") into its bin directory. The wrapper activates the right gem version and then loads your script:
#!C:/Ruby40-x64/bin/ruby.exe
#
# This file was generated by RubyGems.
# ...
require 'rubygems'
Gem.use_gemdeps
version = ">= 0.a"
# ... allows `wordfreq _0.1.0_ args` to pick a specific installed version ...
if Gem.respond_to?(:activate_and_load_bin_path)
Gem.activate_and_load_bin_path('wordfreq', 'wordfreq', version)
else
load Gem.activate_bin_path('wordfreq', 'wordfreq', version)
end
On Windows it also writes wordfreq.bat (@ruby.exe "%~dpn0" %*), so the command works in cmd.exe and PowerShell. Because of these wrappers, your executable doesn't need to be marked executable, and it doesn't need the right shebang for the user's system.
Installing into a throwaway directory is a good way to test a package without touching your real gems. Set GEM_HOME for the install and when you run it:
$ GEM_HOME=/tmp/gemtest gem install ./wordfreq-0.1.0.gem
$ GEM_HOME=/tmp/gemtest /tmp/gemtest/bin/wordfreq --version
wordfreq 0.1.0
$ gem uninstall wordfreq -x
Removing wordfreq
Successfully uninstalled wordfreq-0.1.0
(-x also removes the executables without asking.)
Publishing
rubygems.org
Create an account on rubygems.org, turn on MFA, check that nobody already uses the name, and push:
$ gem signin
$ gem push pkg/wordfreq-0.1.0.gem
Then anyone can gem install wordfreq. A version you've pushed is permanent: you can gem yank it, but you can't reuse that version number. To fix a mistake, bump VERSION and push again. Use semantic versioning so ~> constraints in other people's projects work as intended.
For CI, rubygems.org supports trusted publishing. You register your GitHub Actions workflow with the gem, and the workflow pushes using a short-lived OIDC token, so no long-lived API key has to be stored as a secret. The rubygems/release-gem action handles this.
Without a public gem server
Not every gem should be public. Bundler can install a gem straight from git or from a directory, and in both cases it builds the gem from the gemspec:
# Gemfile of a project that uses wordfreq
source "https://rubygems.org"
gem "rainbow", "~> 3.1"
gem "wordfreq", git: "https://github.com/janedoe/wordfreq.git", tag: "v0.1.0"
# or, for a checkout next to this project:
# gem "wordfreq", path: "../wordfreq"
For many internal gems, run a private gem server (Gemstash, GitHub Packages, Artifactory, Gemfury). Push with gem push --host https://gems.example.com, and add a source "https://gems.example.com" do ... end block in the Gemfile. To keep rake release from pushing a private gem to rubygems.org by accident, set spec.metadata["allowed_push_host"] to your server's URL in the gemspec.
Deploying an application with Bundler
Applications (web apps, workers, internal tools) usually aren't packaged as gems. You ship the source tree together with Gemfile.lock, and Bundler recreates the exact same set of gems on the target machine. The lockfile pins every version and, in Bundler 4, also records checksums:
PATH
remote: ../wordfreq
specs:
wordfreq (0.1.0)
GEM
remote: https://rubygems.org/
specs:
rainbow (3.1.1)
PLATFORMS
x64-mingw-ucrt
DEPENDENCIES
rainbow (~> 3.1)
wordfreq!
CHECKSUMS
rainbow (3.1.1) sha256=039491aa3a89f42efa1d6dec2fc4e62ede96eb6acd95e52f1ad581182b79bc6a
wordfreq (0.1.0)
BUNDLED WITH
4.0.20
Commit Gemfile.lock for applications. If you deploy to Linux from a Mac or Windows machine, add the server's platform with bundle lock --add-platform x86_64-linux, so Bundler can resolve precompiled native gems for it.
On the server, switch Bundler to deployment mode. It then refuses to change the lockfile, installs into vendor/bundle, and skips development gems:
$ bundle config set --local deployment true
$ bundle config set --local without development
$ bundle install
Gems in the group 'development' were not installed.
Bundled gems are installed into `./vendor/bundle`
$ cat .bundle/config
---
BUNDLE_DEPLOYMENT: "true"
BUNDLE_WITHOUT: "development"
The old bundle install --deployment flag has been removed. Use the config settings above instead.
To run the app's commands with the locked gems, either prefix them with bundle exec, or generate project binstubs that do the same thing:
$ bundle binstubs wordfreq
$ ls bin
wordfreq wordfreq.cmd
$ bin/wordfreq -v
wordfreq 0.1.0
Standalone bundles
bundle install --standalone goes one step further. It writes bundle/bundler/setup.rb, a plain file of $LOAD_PATH entries, so at runtime the program needs neither Bundler nor RubyGems:
$ bundle install --standalone
Bundled gems are installed into `./bundle`
$ tail -2 bundle/bundler/setup.rb
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rainbow-3.1.1/lib")
$:.unshift File.expand_path("#{__dir__}/../../../wordfreq/lib")
$ ruby --disable-gems -r ./bundle/bundler/setup report.rb sample.txt
the 4
fox 3
dog 2
Startup is faster as a result: about 0.1 s here, against about 0.9 s for bundle exec, which has to resolve the Gemfile on every run. You can copy the whole directory to another machine with the same Ruby version and platform.
Docker
The most common way to deploy a Ruby service is a container image built from the lockfile. Copy the Gemfile and lockfile first so Docker caches the bundle install layer between code changes:
FROM ruby:4.0-slim
WORKDIR /app
ENV BUNDLE_DEPLOYMENT=1 BUNDLE_WITHOUT=development:test
COPY Gemfile Gemfile.lock ./
RUN bundle install && rm -rf vendor/bundle/ruby/*/cache
COPY . .
CMD ["bundle", "exec", "ruby", "app.rb"]
If you have gems with C extensions that aren't precompiled for Linux, use a multi-stage build: install build-essential and run bundle install in the first stage, then copy /app/vendor/bundle into a slim final image.
Standalone executables for end users
People who don't use Ruby shouldn't have to install it to run your tool. For them, packagers bundle the Ruby interpreter, the standard library, your gems and your code into a single executable.
OCRAN (Windows)
OCRAN (a maintained fork of OCRA) builds a Windows .exe. It runs your script once at build time and records every file the script loads. So the script must require everything it needs, and it must not block or do real work during that run. While OCRAN is running the script, the constant Ocran is defined, so you can check for it:
# wordfreq.rb - entry point for the packager
require_relative "lib/wordfreq"
# OCRAN runs this file once at build time to see what it requires.
# Defining Ocran tells us we're in that run, so don't wait for stdin.
exit Wordfreq::CLI.start(ARGV) unless defined?(Ocran)
$ gem install ocran
$ ocran wordfreq.rb --output wordfreq.exe
...
=== Detected gem optparse-0.8.1 (loaded, files)
=== Including 61 encoding support files (3772416 bytes, use --no-enc to exclude)
...
=== Finished building wordfreq.exe (5012388 bytes)
=== After decompression, the data will expand to 24964441 bytes.
The result is a 5 MB executable that runs on a machine with no Ruby installed:
$ wordfreq.exe -n 3 sample.txt
4 the
3 fox
2 dog
$ echo the end the | wordfreq.exe
2 the
1 end
When it starts, the exe unpacks itself into a temporary directory and runs the bundled ruby.exe from there. ENV["OCRAN_EXECUTABLE"] holds the path of the .exe itself, so use it rather than __dir__ to find files that ship next to the executable. Other useful options: --gemfile Gemfile to include the gems from a Gemfile, --icon app.ico to set the icon, --windows for GUI programs (no console window), and --innosetup to produce an installer.
Watch out for arguments after -- on the OCRAN command line. They're passed to the script during the build run, but they are also baked into the exe as default arguments. Running ocran wordfreq.rb -- sample.txt produces an exe that always reads sample.txt in addition to whatever the user passes. That's why the example above uses defined?(Ocran) instead of giving the build run a file to process.
Tebako (Linux, macOS, Windows)
Tebako takes a different approach. It compiles a Ruby interpreter with your application embedded in a read-only in-memory filesystem, so nothing is extracted at startup. It needs a full C/C++ toolchain to build the runtime, and it's usually run from its prebuilt Docker images:
tebako press --root=. --entry-point=wordfreq.rb --output=wordfreq
Expect binaries of 20 to 40 MB. Every target OS and CPU architecture needs its own build.
Summary
- One file: shebang plus
bundler/inline. - Anything larger: make it a gem. Keep logic in
lib/and a thin wrapper inexe/, list the files explicitly, and build withgem buildorrake build. - Test the package by installing the
.gemlocally (into a scratchGEM_HOME) before you push it. - Publish with
gem push(with MFA or trusted publishing), or use git, path or a private server for internal code. - Deploy applications from
Gemfile.lockwith Bundler's deployment settings. Use a Docker image or a--standalonebundle. - For users without Ruby, package a self-contained executable with OCRAN or Tebako.