Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects and Practice

Project: A To-Do Command-Line App in Crystal

Build a command-line to-do app in Crystal step by step: structs, JSON storage, OptionParser, subcommands, errors and specs, with a runnable Ruby version of the logic.

In this project you will design a small command-line program, todo, that adds, lists, completes and removes tasks and stores them in a JSON file. It touches many earlier ideas: typed collections, named data, blocks, Enumerable and JSON.

The compiler is not on this site, so the Crystal files are read-only listings that we have checked by reading. The runnable Ruby version of the same logic lets you run and extend every behavior: the model, the commands and the storage.

The plan

TEXT
todo add "Buy milk"        # adds a task
todo list                  # shows all tasks
todo list --open           # only unfinished tasks
todo done 2                # marks task 2 as done
todo remove 3              # deletes task 3

Project layout:

TEXT
todo/
  shard.yml
  src/todo.cr         # entry point, option parsing
  src/todo/task.cr    # the Task type
  src/todo/store.cr   # reads and writes the JSON file
  spec/store_spec.cr
flowchart LR
  CLI["OptionParser: parse the command"] --> S["Store: load tasks"]
  S --> A["Apply: add / done / remove"]
  A --> W["Store: save tasks"]
  A --> P["Print result"]

The command line decides what to do; the store only knows how to load and save.

Step 1: the Task type

CRYSTAL
require "json"

struct Task
  include JSON::Serializable

  getter id : Int32
  getter title : String
  getter? done : Bool

  def initialize(@id : Int32, @title : String, @done : Bool = false)
  end

  def complete : Task
    Task.new(@id, @title, true)
  end

  def to_line : String
    mark = done? ? "x" : " "
    "[#{mark}] #{id}. #{title}"
  end
end

A struct is a value type: copying is cheap and complete returns a new task instead of mutating, which suits a small immutable record. getter? done defines done?, the Crystal naming convention for booleans.

Step 2: the Store

The store keeps the list in memory and syncs it with a file:

CRYSTAL
class Store
  getter tasks : Array(Task)

  def initialize(@path : String)
    @tasks = File.exists?(@path) ? Array(Task).from_json(File.read(@path)) : [] of Task
  end

  def add(title : String) : Task
    task = Task.new(next_id, title)
    @tasks << task
    task
  end

  def complete(id : Int32) : Task
    index = @tasks.index { |t| t.id == id } || raise ArgumentError.new("No task with id #{id}")
    @tasks[index] = @tasks[index].complete
  end

  def remove(id : Int32) : Task
    index = @tasks.index { |t| t.id == id } || raise ArgumentError.new("No task with id #{id}")
    @tasks.delete_at(index)
  end

  def save
    File.write(@path, @tasks.to_pretty_json)
  end

  private def next_id : Int32
    (@tasks.max_of?(&.id) || 0) + 1
  end
end

Array(Task).from_json is the typed mapping from the JSON lesson: a corrupted file raises a clear error instead of loading garbage. The || raise ... idiom handles the nil from index in one line.

Step 3: the Ruby version you can run

Ruby Ruby stand-in: Task and Store (in memory)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Step 4: the command line

OptionParser in the standard library handles flags and gives automatic --help:

CRYSTAL
require "option_parser"
require "./todo/*"

only_open = false
parser = OptionParser.new do |p|
  p.banner = "Usage: todo <command> [arguments]"
  p.on("--open", "List only unfinished tasks") { only_open = true }
  p.on("-h", "--help", "Show this help") do
    puts p
    exit
  end
  p.invalid_option do |flag|
    STDERR.puts "Unknown option: #{flag}"
    exit 1
  end
end

args = parser.parse          # returns the remaining, non-flag arguments
store = Store.new(File.join(Dir.current, "todo.json"))

begin
  case args.shift?
  when "add"
    title = args.join(" ")
    abort "Give the task a title" if title.empty?
    puts "Added: #{store.add(title).to_line}"
  when "list"
    tasks = only_open ? store.tasks.reject(&.done?) : store.tasks
    tasks.each { |t| puts t.to_line }
    puts "(no tasks)" if tasks.empty?
  when "done"
    id = args.first?.try(&.to_i?) || abort "Usage: todo done ID"
    puts "Done: #{store.complete(id).to_line}"
  when "remove"
    id = args.first?.try(&.to_i?) || abort "Usage: todo remove ID"
    puts "Removed: #{store.remove(id).to_line}"
  else
    puts parser
    exit 1
  end
  store.save
rescue ex : ArgumentError
  abort "Error: #{ex.message}"
end

Notice the flow: parse flags, dispatch on the first remaining word, perform the change, save once at the end. abort prints to standard error and exits with code 1, and the nilable to_i? guards against todo done banana.

Ruby Ruby stand-in: dispatching commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Step 5: specs

A spec for the store checks behavior with a temporary file (see Testing with Spec):

CRYSTAL
require "spec"
require "../src/todo/*"

describe Store do
  it "numbers new tasks from 1" do
    store = Store.new(File.tempname("todo", ".json"))
    store.add("a").id.should eq(1)
    store.add("b").id.should eq(2)
  end

  it "marks a task done without touching the others" do
    store = Store.new(File.tempname("todo", ".json"))
    store.add("a")
    store.add("b")
    store.complete(2)
    store.tasks.map(&.done?).should eq([false, true])
  end

  it "reports an unknown id" do
    store = Store.new(File.tempname("todo", ".json"))
    expect_raises(ArgumentError, "No task with id 9") { store.remove(9) }
  end
end

Ideas to extend it

  1. A due date using Time and a list --overdue filter.
  2. Priorities with an enum Priority, sorted with sort_by.
  3. Tags stored in a Set(String) and list --tag home.
  4. Colors in the output with String#colorize (require "colorize").
  5. Build a release binary with shards build --release and put it on your PATH.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is Task a struct rather than a class in this design?

    A struct is copied by value, which fits small immutable records; classes would also work.
  2. 2. What does args.first?.try(&.to_i?) protect against?

    first? is nil when there is no argument, and to_i? is nil for non-numbers, so todo done banana fails politely.
  3. 3. Why does Store load with Array(Task).from_json?

    Typed deserialization validates every field.
  4. 4. Which part of the program decides which command runs?

    Parsing flags leaves the command word first in the remaining arguments, and case dispatches on it.

Summary

  • Keep the model (Task), storage (Store) and interface (command line) separate.
  • struct + JSON::Serializable gives a typed record that saves and loads itself.
  • OptionParser parses flags and builds --help for you; abort ends with a message and code 1.
  • Nilable lookups (first?, to_i?, index) plus || raise handle bad input compactly.
  • Write specs against the store, not the terminal.

Next: Project: A Tiny Web Router and URL Shortener