Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 134 ยท Projects

Project: Command-Line To-Do Manager

Build a to-do manager in Ruby with Data objects, an Enumerable collection, custom errors, JSON saving and loading, pattern-matching command parsing and a scripted command loop you can run in the browser.

A to-do list is the classic first real program, because it contains the skeleton of almost every application: some data (tasks), some rules (a title cannot be empty), a collection with operations (add, complete, remove, filter), persistence (save it so it survives), and a user interface that turns what a person types into those operations. In this project you build all five parts as separate, small, testable pieces and then snap them together.

We will use a command-line style: you type add Buy milk !1 #home, and the program answers. A real terminal tool would read from the keyboard; here the lesson's editor feeds it a prepared list of commands, so you can run the whole thing in your browser. Our "disk" is a StringIO object, an in-memory stand-in for a file (StringIO and Streams), because the runner's files vanish after each run. Swapping it for File.open later is a one-line change, and that is exactly the point of designing the storage as a separate piece.

The finished program will support:

TEXT
add TEXT [!1-3] [#tag ...]   add a task (priority 1 is the most urgent)
list [#tag]                  show pending tasks, optionally one tag
all                          show every task including finished ones
done ID                      mark a task as finished
remove ID                    delete a task
stats                        counts by state and priority
save / load                  write to and read from storage
quit                         leave the program

Step 1: the task as a value

What is a task? A title, a priority, some tags, and whether it is finished, plus an id so we can refer to it. We could use a Struct or a plain class, but a task is a value: it has no life of its own, and it is easier to reason about when it cannot change behind your back. Data gives us exactly that. To "complete" a task we do not mutate it; we produce a new one with with.

We also want validation, so a broken task can never exist. Overriding initialize in a Data class lets us supply defaults and check rules in one place.

Ruby Step 1: Task as an immutable Data class

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.

Three things to notice. The title was cleaned with strip while building, so every Task in the program is already tidy. complete returned a different object: milk is still not done, which means any list holding milk is unaffected until we deliberately replace it. And invalid input fails at the moment of creation, with a message that says what was wrong and what was received. Ruby protects the immutability, as this example (which fails on purpose) shows:

Ruby Trying to change a Data object (fails on purpose)

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.

Data classes define readers but no writers, so the call fails with undefined method 'done=' for an instance of Task (NoMethodError). Ruby 4.0 also appends a short excerpt of the offending source line to such messages. The fix is not to give the class a writer, but to ask for a changed copy: task.with(done: true).

Step 2: the collection

A single task is not an application. We need a list that can add, find, complete and remove tasks, and answer questions about them. A class TodoList will own an array of tasks and hand out ids. Two decisions make it pleasant:

  • It includes Enumerable and defines each. For free we get select, sort_by, count, group_by, partition, min_by, and the rest of the toolbox.
  • Looking up a missing id raises our own error, TaskNotFound, so callers cannot silently ignore it. (Custom Exceptions explains why a dedicated class is worth it.)
Ruby Step 2: the TodoList collection

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.

Pay attention to the line @tasks[@tasks.index(task)] = task.complete. Because tasks are immutable, "completing" means replacing the old object in the array with its updated copy. Also notice that the id of the new task is 5, not 3: ids come from a counter, never from reusing a freed number, so an id you saw earlier can never point at a different task later. The sorting key [it.priority, it.id] is an array; Ruby compares arrays element by element, giving "priority first, then id" with no extra code.

Step 3: saving and loading

Persistence means turning the in-memory objects into text and back. JSON is a convenient format (JSON): Data#to_h gives a hash, JSON.generate turns the array of hashes into text, and JSON.parse(text, symbolize_names: true) reverses it. Because Task.new validates, loading data that someone edited by hand (and broke) will be caught instead of silently producing bad objects.

The storage logic gets its own class and takes the IO object as a parameter. It does not know whether it writes to a file or to memory. Programs written this way are easy to test, which is the same principle as in Test Doubles.

Ruby Step 3: saving to and loading from an in-memory file

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.

The round trip works: the restored array equals the original, since Data compares by value. Wrapping low-level problems (JSON::ParserError, ArgumentError) in our own StorageError is a pattern worth copying. The caller of load should only need to know one thing that can go wrong, "the storage is unusable", and not the names of the libraries used inside.

In a real tool, saving should be atomic: write to a temporary file first and rename it over the old one, so a crash in the middle never leaves a half-written file. File.write(path + ".tmp", json) followed by File.rename(path + ".tmp", path) does it. See Files and IO.

Step 4: understanding the commands

The user types text like add Buy milk !1 #home. Before running anything, we parse it into an object that says what is wanted. Separating "understand the input" from "do the work" means the parser can be tested without touching the list at all.

The parser splits the line into a command word and the rest, then uses pattern matching to recognise each shape. Regular expressions pull the priority and tags out of the text of an add, and a Data object per command carries the result.

Ruby Step 4: parsing commands with pattern matching

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.

Look at how the pattern ["done", /\A\d+\z/ => id] does three jobs at once: it checks the command word, checks that the argument looks like a number with a regular expression, and binds the matched text to id. If the argument is not numeric, the next, more general, pattern produces a helpful error. The final pattern [word, *] catches everything else, so unknown commands never fall through unnoticed. (Without a final catch-all, case/in raises NoMatchingPatternError when nothing matches, which would be a bug, not a user error.) Note too that Fix C# parser keeps its C#: the tag pattern requires # to start a word and be followed by a word character.

Step 5: putting it together

Now the application class. It owns a TodoList, a Storage, and the "disk", and has one method per command. Its execute method takes a parsed command and uses case/in once more, this time on the command objects. The main loop reads lines, parses, executes, and catches the three families of errors we defined (CommandError, TaskNotFound, StorageError). Any other exception is a genuine bug and is allowed to crash with a stack trace.

Run the program below. The scripted input does a bit of everything: it adds tasks, completes one, makes mistakes on purpose, saves, deletes everything, and then loads the saved state back.

Ruby Step 5: the complete to-do manager

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.

Read the transcript as a story. The ! lines come from the three error families: done 42 raises TaskNotFound, add with no text and frobnicate raise CommandError. The program prints the message and keeps going, rather than crashing. After save, three tasks are removed and list answers "(nothing to show)", because the one task left is already finished and list shows only pending work. load brings everything back, with the finished task still finished, because the done flag travelled through JSON. The last line of the input, after quit, is never read: break ends the loop.

Two small Ruby ideas appear in run. command = parse_command(line) or next skips blank lines (parse_command returns nil for them), and command in Simple[name: "quit"] is a boolean pattern test, handy when you only want a yes or no answer without a full case. Inside execute, the keyword patterns such as Add[title:, priority:, tags:] unpack a command's fields into local variables with matching names.

Design review: what makes this version good

Look back at the structure. Each class has one job and knows nothing about the others' internals:

  • Task knows its own rules and nothing about lists.
  • TodoList manages a collection; it never prints.
  • Storage converts between tasks and text, and does not know where the text lives.
  • parse_command turns text into command objects without touching any state.
  • TodoApp is the only class that prints, and it wires the others together.

That separation (compare Design Principles in Ruby) is what lets you test every piece alone. For instance, a Minitest test for parse_command needs no list, no storage and no output. And swapping the interface, say for a web page with Sinatra, only requires replacing TodoApp.

Ideas for extending it

  1. Due dates. Add a due field holding a Date, parse due:2026-12-24, and add an overdue command (Time and Date).
  2. Edit and undo. Because tasks are immutable, an undo stack is just a list of previous arrays of tasks.
  3. Search. Add find TEXT with a case-insensitive regular expression.
  4. Real files. Replace the StringIO with File.open plus the atomic-rename trick from the note above.
  5. Real command line. Read ARGV for one-shot use (todo add "Buy milk") and fall back to the interactive loop (Scripting and Command-Line Tools).
  6. Tests. Write Minitest cases for the parser table in Step 4 (Testing with Minitest).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does task.complete return a new Task instead of changing the existing one?

    Data classes have no setters. Immutability means an object never changes behind your back, so updates produce a modified copy that you store in place of the old one.
  2. 2. What do you get from including Enumerable in TodoList and defining each?

    Enumerable builds its whole toolbox on top of each, so any class that yields its items gets the collection methods for free.
  3. 3. Why does Storage#load convert JSON::ParserError and ArgumentError into StorageError?

    Callers should not have to know which libraries are used inside. A single StorageError says what matters: the stored data cannot be used.
  4. 4. What happens if the final catch-all pattern is removed from case/in in parse_command and the user types dance?

    Unlike case/when, case/in raises NoMatchingPatternError when no pattern matches and there is no else branch, so a catch-all that raises a friendly CommandError is better.
  5. 5. Why do ids come from a counter instead of reusing the lowest free number?

    If freed ids were reused, an old done 3 typed after a deletion could finish a brand new, unrelated task. A counter keeps each id unique for the life of the list.

Summary

  • Model the data as an immutable Data class with validation in initialize; change it with with, which returns a copy.
  • A collection class that includes Enumerable and defines each gets the whole iteration toolbox for free.
  • Define small custom error classes for the failures a user can cause, and rescue exactly those in the main loop.
  • Persist by converting to hashes and JSON; take the IO object as a parameter so storage works with files, StringIO or anything else.
  • Parse text into command objects first, with case/in patterns and regular expressions, then execute them in a second step.
  • Keep each class focused on one job, and let one outer class do the printing and wiring.

Next: Project: Bank Account Simulation