Capstone: todo CLI
| The spec | |
| OptionParser | |
| JSON file store | |
| Minitest for the store |
The spec
The first capstone is a command line todo manager backed by one JSON file. Three commands cover the whole behavior: add a task, list tasks, and mark a task done.
Everything uses only the Ruby standard library, so the project runs anywhere Ruby runs.
ruby todo.rb --add "Buy milk"
ruby todo.rb --list
ruby todo.rb --done 1
OptionParser
OptionParser turns flags into a plain options hash with help text included. Describe each flag once with names, a placeholder, and a short label.
Parse with a bang method so processed flags leave ARGV and the rest of the program sees only plain arguments.
require "optparse"
options = {}
OptionParser.new do |opts|
opts.on("-a", "--add TITLE", "Add a todo") do |v|
options[:add] = v
end
opts.on("-l", "--list", "List todos") { options[:list] = true }
end.parse!
puts options.inspect
JSON file store
The store module hides all file details behind read and write methods. Read returns an empty array when the file does not exist yet.
Pretty generate keeps the file human readable, which makes debugging the CLI far easier.
require "json"
module Store
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
Minitest for the store
Test the store before wiring the CLI around it. One round trip test writes an item and reads it back with an equality check.
Run the test file directly and minitest reports pass or fail with a short summary line.
require "minitest/autorun"
require_relative "store"
class TestStore < Minitest::Test
def test_write_and_read
Store.write([{ "title" => "x" }])
assert_equal("x", Store.read.first["title"])
end
end
Next: Capstone: JSON API
Article author: Arthur Isaev