Project: package the CLI as a gem

The library

The todo CLI from lesson 13.29 becomes a gem in three files: the library, the command, and the gemspec that ties them together. The library keeps the version constant and the JSON file handling:

lib/todo.rb

require "json" module Todo VERSION = "0.1.0" FILE = "todos.json" def self.read return [] unless File.exist?(FILE) JSON.parse(File.read(FILE)) end def self.write(items) File.write(FILE, JSON.pretty_generate(items)) end end

The command

The command lives in exe/, requires the library by its gem name, and parses the three flags from the capstone lesson:

exe/todo

#!/usr/bin/env ruby require "optparse" require "todo" options = {} OptionParser.new do |parser| parser.on("-a", "--add TITLE", "Add a todo") { |value| options[:add] = value } parser.on("-l", "--list", "List todos") { options[:list] = true } parser.on("-d", "--done N", Integer, "Mark a todo done") { |value| options[:done] = value } end.parse! items = Todo.read if options[:add] items << { "title" => options[:add], "done" => false } Todo.write(items) end if options[:done] items[options[:done] - 1]["done"] = true Todo.write(items) end if options[:list] || options.empty? items.each_with_index { |item, index| puts "#{index + 1}. #{item["title"]}#{" (done)" if item["done"]}" } end

The gemspec

The gemspec reads the version from the library and names the executable, so a new release is one constant and one build:

todo.gemspec

require_relative "lib/todo" Gem::Specification.new do |spec| spec.name = "todo" spec.version = Todo::VERSION spec.summary = "A tiny todo list for the terminal" spec.authors = ["Arthur Isaev"] spec.license = "MIT" spec.homepage = "https://example.com/todo" spec.files = ["lib/todo.rb", "exe/todo"] spec.bindir = "exe" spec.executables = ["todo"] spec.require_paths = ["lib"] spec.required_ruby_version = ">= 3.0" end

Build and install

Give the executable its execute bit first: RubyGems warns about a file in exe/ without one, and the warning is not part of a clean build.

chmod +x exe/todo

gem build todo.gemspec

Successfully built RubyGem
Name: todo
Version: 0.1.0
File: todo-0.1.0.gem

gem install ./todo-0.1.0.gem

Successfully installed todo-0.1.0
1 gem installed

A Ruby with rdoc installed adds its own documentation lines between those two; the gem is installed either way.

Use it

The command now works from any folder, and it writes its JSON file in the folder it runs in:

todo --add "Buy milk"

todo --add "Write tests"

todo --list

1. Buy milk
2. Write tests

todo --done 1

todo --list

1. Buy milk (done)
2. Write tests

cat todos.json

[ { "title": "Buy milk", "done": true }, { "title": "Write tests", "done": false } ]

What to watch for

Write the JSON file next to the working folder, not next to the gem. A gem installed system-wide lives under the Ruby installation, and a data file there is invisible to the user and lost on the next update.

Test the installed command, not only the source: build, install, run todo --list. A file missing from spec.files works from the project folder and fails from the gem.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Where does gem build read the gem name, version and file list from?

    Answer

    The gemspec

    The gemspec is the description of the package: name, version, files, executable and load path.

  2. What does spec.executables = ["todo"] do?

    Answer

    Installs todo as a command from the bindir

    RubyGems puts a wrapper for the named executable in the gem bin folder, which is on PATH after install.

  3. Why does the gemspec load lib/todo with require_relative?

    Answer

    To get the version constant while the gem is built

    The version lives in one place, and the build reads it from the library instead of repeating the string.

  4. Why does the command write todos.json in the folder it runs in?

    Answer

    A gem folder is replaced on update, so data there is lost

    The user's data belongs to the user; the gem folder is a package that a new version replaces.

  5. What does this program print? require "optparse" options = {} OptionParser.new do |parser| parser.on("-n", "--name NAME") { |value| options[:name] = value } end.parse!(["--name", "Ada"]) p options

    Answer

    {name: "Ada"}

    The block stores the value under a symbol key, and the modern inspect prints that hash as {name: "Ada"}.

  6. What does this program print? require "json" items = [{ "title" => "Buy milk", "done" => false }] puts JSON.generate(items)

    Answer

    [{"title":"Buy milk","done":false}]

    The array of one hash becomes an array of one object, all on one line with generate.

  7. What does this program print? items = [{ "title" => "Buy milk", "done" => true }, { "title" => "Write tests", "done" => false }] items.each_with_index { |item, index| puts "#{index + 1}. #{item["title"]}#{" (done)" if item["done"]}" }

    Answer

    1. Buy milk (done) / 2. Write tests

    The first item is done and the second is not, so only the first line carries the marker.

  8. What does this program print? module Todo VERSION = "0.1.0" end p Todo::VERSION

    Answer

    "0.1.0"

    p prints the string with its quotes, which is why the version in output is shown as a quoted value.

  9. A command file is used from the project but missing from spec.files. What happens after install?

    Answer

    The command fails because the packaged gem lacks the file

    The project folder has every file; the built gem has only the files the gemspec lists.

  10. The command receives --done 0 and runs items[n - 1]["done"] = true. What happens?

    Answer

    It marks the last item, because index -1 is the end of the array

    Ruby reads -1 as the last element, so a missing lower bound check turns 0 into the opposite end of the list.

Article author: Arthur Isaev