Thuta Learning
Ruby
AdvancedProgrammingBeginner

Mini Project

RubyLesson 2845 min

What you'll walk away with

  • Structure a program into data, logic, command and persistence layers plus a driver
  • Route command strings with split and case, and turn expected errors into messages
  • Save a task list as JSON and read it back with symbolize_names
  • Use Dir.mktmpdir to exercise file-writing code without touching your own files

Explain it simply

Explain it simply

A mini project is where the pieces taught in separate lessons finally work together in one program. In a task tracker, each task is a hash, all tasks live in an array, and each command such as "add" or "done" is handled by a method. If you save them to a file, they are still there when the program starts again tomorrow.

This time the program does not wait for the keyboard. "What the user types" is written into the program as a list of commands, and the program reads them one line at a time. That gives identical output on this page, and it is also exactly what you need later when you write tests.

Problem → Why → Solution

The problem: input, logic and data welded together

Writing the first menu program with gets directly inside a loop seems to work. But the code below has three problems. First, gets.chomp crashes with undefined method 'chomp' for nil when the input ends (Ctrl-D, or the end of a pipe), because gets then returns nil; that is the message wording of Ruby 4.0.9. Second, all logic is welded to gets and puts, so nobody can try it without a person typing. Third, everything in the tasks array disappears the moment the program exits.

These problems barely hurt in a tiny project but get worse with every feature you add. The cure is to separate layers.

tangled_tracker.rb
tasks = []

loop do
  print "Choose (1 add, 2 list, 3 quit): "
  choice = gets.chomp           # NoMethodError when the input ends: gets returns nil
  if choice == "1"
    print "Title: "
    tasks << { title: gets.chomp, done: false }
  elsif choice == "2"
    tasks.each { |task| puts task[:title] }
  elsif choice == "3"
    break
  end
end                             # everything in tasks is lost here

Why separate layers?

Reading input, understanding a command, changing data, showing the result and saving to a file are five different jobs. When each lives in its own method or class, fixing one does not disturb the others, and each can be tried on its own.

Core concept: a program in five layers

Our tracker has five layers, and each does exactly one job. A command line travels from the top down and comes back as a line of text.

1. Data: hashes as tasks

Each task is a hash like { id: 1, title: "Learn blocks", done: false }. The id identifies a task without depending on its index in the array, so it stays valid even after you later delete something.

2. Logic: the TaskList class

add, complete and lines only change or return data, with no puts or gets. Invalid use raises ArgumentError or UnknownTask. Because there is no I/O, you can test the class directly with Minitest.

3. Commands: the handle method

A line such as "done 1" is split into a command and an argument with split(" ", 2), and case calls the right method. The result is returned as a string instead of printed, and expected errors become an "Error: ..." message.

4. Persistence: a JSON file

save writes the tasks to a file as JSON text and load reads them back. Passing symbolize_names: true turns the keys back into symbols such as :id and :title, so the rest of the code keeps working.

5. Driver: the loop that feeds commands

The loop at the bottom sends each command to handle and prints the result. Only this layer knows where commands come from: it is a script array now, and in a terminal you can swap in $stdin.gets.

To exercise code that writes files without touching your own, use Dir.mktmpdir. It creates a temporary folder and deletes it, with its files, as soon as the block ends, so running this project over and over leaves nothing behind.

Mental model: the journey of one command
  1. The driver supplies a command line
  2. handle splits command and argument
  3. TaskList changes data or raises
  4. A result string comes back to print

With no puts or gets in the logic, you can call it from anywhere, including a test.

General pattern

ruby
def handle(store, line)
  command, argument = line.split(" ", 2)
  case command
  when "add"  then store.add(argument)
  when "done" then store.complete(Integer(argument))
  else "Unknown command: #{command.inspect}"
  end
rescue ArgumentError, StoreError => e
  "Error: #{e.message}"
end

The line is split into its first word and the rest, and case picks the action. A method-level rescue catches only the error types you expect and turns them into messages; unexpected bugs still surface.

Example: running the Task Tracker from a script

This one file contains all five layers. The script array mixes good commands with bad ones: an add with no title, an id that does not exist, an id that is not a number and an unknown command. Afterwards it saves, loads a brand-new task list from the file in the temp folder and prints it, proving the data survived. Read the results and find where each error message comes from.

task_tracker.rb
require "json"
require "tmpdir"

class TaskList
  class UnknownTask < StandardError; end

  def initialize(tasks = [])
    @tasks = tasks
  end

  def add(title)
    title = title.to_s.strip
    raise ArgumentError, "title can't be blank" if title.empty?

    task = { id: next_id, title: title, done: false }
    @tasks << task
    task
  end

  def complete(id)
    task = @tasks.find { |candidate| candidate[:id] == id }
    raise UnknownTask, "no task with id #{id}" unless task

    task[:done] = true
    task
  end

  def lines
    return ["(no tasks yet)"] if @tasks.empty?

    @tasks.map do |task|
      mark = task[:done] ? "x" : " "
      "#{task[:id]}. [#{mark}] #{task[:title]}"
    end
  end

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

  def self.load(path)
    return new unless File.exist?(path)

    new(JSON.parse(File.read(path), symbolize_names: true))
  end

  private

  def next_id = (@tasks.map { |task| task[:id] }.max || 0) + 1
end

def handle(list, line, path)
  command, argument = line.split(" ", 2)
  case command
  when "add"
    task = list.add(argument)
    "Added ##{task[:id]}: #{task[:title]}"
  when "done"
    task = list.complete(Integer(argument))
    "Completed ##{task[:id]}"
  when "list"
    list.lines.join("\n")
  when "save"
    list.save(path)
    "Saved to #{File.basename(path)}"
  else
    "Unknown command: #{command.inspect}"
  end
rescue ArgumentError, TypeError, TaskList::UnknownTask => e
  "Error: #{e.message}"
end

script = [
  "add Learn blocks",
  "add Write a Minitest file",
  "add   ",
  "done 1",
  "done 9",
  "done abc",
  "list",
  "save",
  "dance"
]

Dir.mktmpdir("task-tracker") do |dir|
  path = File.join(dir, "tasks.json")
  list = TaskList.load(path)

  script.each do |line|
    puts "> #{line.strip}"
    puts handle(list, line, path)
  end

  puts "--- next session ---"
  puts TaskList.load(path).lines
  puts File.read(path)
end

Code breakdown

  1. Custom errorclass UnknownTask < StandardError; end

    Defining an error class inside TaskList lets callers catch "no such task" separately instead of mixing it up with other errors such as ArgumentError.

  2. Task hashtask = { id: next_id, title: title, done: false }

    A task is a plain hash. next_id takes the largest existing id and adds 1, so every new task gets an id nobody else has.

  3. Parsing a commandcommand, argument = line.split(" ", 2)

    split(" ", 2) splits only at the first space and returns at most two parts. "add Learn blocks" becomes "add" and "Learn blocks", so spaces inside the title survive. A bare "add" leaves argument as nil.

  4. Expected errors onlyrescue ArgumentError, TypeError, TaskList::UnknownTask => e

    This rescue catches only the errors you know can happen: a blank title (ArgumentError), "done abc" (Integer()'s ArgumentError), a bare "done" (a TypeError for nil) and a missing id (UnknownTask). It does not hide any other bug.

  5. Loadingnew(JSON.parse(File.read(path), symbolize_names: true))

    Reads the file and parses the JSON. Without symbolize_names: true the keys would be the strings "id" and "title", and task[:title] would return nil. This line builds a fresh TaskList from the result.

  6. Temp folderDir.mktmpdir("task-tracker") do |dir|

    Creates a temporary folder and removes everything when the block ends. That is why the output shows only the name tasks.json through File.basename, not the full path, which differs on every computer.

You should see
> add Learn blocks
Added #1: Learn blocks
> add Write a Minitest file
Added #2: Write a Minitest file
> add
Error: title can't be blank
> done 1
Completed #1
> done 9
Error: no task with id 9
> done abc
Error: invalid value for Integer(): "abc"
> list
1. [x] Learn blocks
2. [ ] Write a Minitest file
> save
Saved to tasks.json
> dance
Unknown command: "dance"
--- next session ---
1. [x] Learn blocks
2. [ ] Write a Minitest file
[
  {
    "id": 1,
    "title": "Learn blocks",
    "done": true
  },
  {
    "id": 2,
    "title": "Write a Minitest file",
    "done": false
  }
]

The JSON round trip and how hashes print

Keys in JSON are always strings, so parsing turns a hash with symbol keys into a hash with string keys, and you only get symbols back with symbolize_names: true. Below you can see both side by side. When you print hashes with p, Ruby 3.4 and newer show {id: 1} and {"id" => 1} (with spaces around =>), whereas older versions printed {:id=>1} and {"id"=>1}. Every output in this lesson comes from Ruby 4.0.9.

round_trip.rb
require "json"

task = { id: 1, title: "Learn blocks", done: false }
text = JSON.generate(task)
puts text                        # {"id":1,"title":"Learn blocks","done":false}

plain = JSON.parse(text)
symbolized = JSON.parse(text, symbolize_names: true)
p plain                          # {"id" => 1, "title" => "Learn blocks", ...}
p symbolized                     # {id: 1, title: "Learn blocks", done: false}
p plain[:title]                  # nil
p symbolized[:title]             # "Learn blocks"

Swapping the script for a real keyboard

To run in a terminal, only the driver loop changes. $stdin.gets returns the line the user typed, and nil when the input ends (Ctrl-D). So you check for nil before touching the line instead of calling gets.chomp directly, which avoids the crash from the problem section. handle, TaskList and the JSON code stay exactly as they are. This snippet depends on list, path and handle from the example above, so it is not run on its own here.

interactive_driver.rb
loop do
  print "> "
  line = $stdin.gets
  break if line.nil? || line.strip == "quit"

  puts handle(list, line, path)
end

In real projects

Where this shows up in real projects

The shape of this project shows up everywhere in professional Ruby code. In Rails, the model holds data and rules, the controller reads a request and chooses what to do, and the view shows the result, just like our TaskList, handle and driver. Command-line tools parse ARGV and dispatch to a handler, much like our handle method. Keeping settings and data in a JSON or YAML file is routine.

Feeding a script of commands is also how real programs are tested. A test passes in a scripted list of commands and checks the messages that come back, with nobody typing, so the Minitest from the previous lesson applies to this project directly. Each new feature (remove, edit, due dates) then needs one more when in handle and one more method in TaskList, with no need to rewrite what already works.

Common mistakes

Common mistakes

1. Reading JSON back without symbolize_names

The keys are strings, so task[:title] is nil, lines prints blanks such as ". [ ] " and find { |t| t[:id] == 1 } returns nil. Because nothing raises, it is worse than a crash. Add symbolize_names: true right where you parse.

2. Not checking gets for nil

Writing gets.chomp directly fails with undefined method 'chomp' for nil when input ends through a pipe or Ctrl-D. Take line = $stdin.gets and break when line.nil?.

3. Putting puts and gets inside the logic

If TaskList#add prints "Added" itself, tests produce stray output, and changing the wording means editing the class. Let the logic return values and leave printing to handle and the driver.

4. Using to_i to parse a number

"abc".to_i returns 0 and "12abc".to_i returns 12, so "done 12abc" could silently complete task 12. Integer("12abc") raises ArgumentError, so the mistake is caught. Use Integer() for user input.

Best practices

Best practices

  • Keep puts, gets and File out of the logic layer; accept a path as an argument so Dir.mktmpdir can exercise it.
  • Do not generate ids as the array's size + 1, because deleting a task can make ids collide; use the largest id + 1.
  • List only the error classes you expect in rescue; a bare rescue also hides typos.
  • Before adding a feature, run the current script and keep its output, so after the change you can see what moved.

Mini challenge

Mini challenge: a shopping list

Build a shopping list with the same structure as the task tracker. Run it from scripted commands, save it to a JSON file in a temp folder, load it back and check that the summary is the same.

  • Item = Struct.new(:name, :bought) and a ShoppingList class with add, buy, remove, summary, save and self.load
  • Buying or removing an item that is not on the list raises NotOnList with a message such as "salt is not on the list"
  • Each script command goes through case, and errors are shown as "Error: ..."
  • summary reads like "1 of 2 bought", and it must be the same after save and load
shopping_list.rb
require "json"
require "tmpdir"

# TODO: Item = Struct.new(:name, :bought)

class ShoppingList
  # TODO: class NotOnList < StandardError

  # TODO: initialize(items = []) keeps an array of Item objects

  # TODO: add(name), buy(name), remove(name)
  #       buy and remove raise NotOnList for a name that is not on the list
  # TODO: summary returns text like "1 of 2 bought"
  # TODO: save(path) writes JSON; self.load(path) rebuilds the list (symbolize_names!)
end

script = [
  "add milk", "add eggs", "add rice",
  "buy eggs", "remove rice", "buy salt", "summary"
]

# TODO: inside Dir.mktmpdir, run every command, rescue NotOnList, then save and reload
#       and print "Reloaded: ..." with the reloaded summary

Expected: Eight lines are printed: Added milk Added eggs Added rice Bought eggs Removed rice Error: salt is not on the list 1 of 2 bought Reloaded: 1 of 2 bought

Show hint

Call item.to_h to put a Struct into JSON, and rebuild with Item.new(row[:name], row[:bought]) on the way back. A private find method that raises NotOnList can be shared by buy and remove.

Show solution
shopping_list.rb
require "json"
require "tmpdir"

Item = Struct.new(:name, :bought)

class ShoppingList
  class NotOnList < StandardError; end

  def initialize(items = [])
    @items = items
  end

  def add(name) = @items << Item.new(name, false)

  def buy(name)
    find(name).bought = true
  end

  def remove(name)
    find(name)
    @items.reject! { |item| item.name == name }
  end

  def summary = "#{@items.count(&:bought)} of #{@items.size} bought"

  def save(path)
    File.write(path, JSON.generate(@items.map(&:to_h)))
  end

  def self.load(path)
    rows = JSON.parse(File.read(path), symbolize_names: true)
    new(rows.map { |row| Item.new(row[:name], row[:bought]) })
  end

  private

  def find(name)
    item = @items.find { |candidate| candidate.name == name }
    raise NotOnList, "#{name} is not on the list" unless item

    item
  end
end

script = [
  "add milk", "add eggs", "add rice",
  "buy eggs", "remove rice", "buy salt", "summary"
]

Dir.mktmpdir("shopping") do |dir|
  path = File.join(dir, "list.json")
  list = ShoppingList.new

  script.each do |line|
    command, name = line.split(" ", 2)
    begin
      case command
      when "add"
        list.add(name)
        puts "Added #{name}"
      when "buy"
        list.buy(name)
        puts "Bought #{name}"
      when "remove"
        list.remove(name)
        puts "Removed #{name}"
      when "summary"
        puts list.summary
      end
    rescue ShoppingList::NotOnList => e
      puts "Error: #{e.message}"
    end
  end

  list.save(path)
  puts "Reloaded: #{ShoppingList.load(path).summary}"
end

Quick quiz 1 / 3

What does "add Learn blocks".split(" ", 2) return?

Quick quiz 2 / 3

You read a task with JSON.parse(text) and ask for task[:title]. The text contains a "title" key. What do you get?

Quick quiz 3 / 3

Which design choice would make this project hard to test?

What to remember

  • Split a program into data, logic, command, persistence and driver layers, and keep puts and gets out of the logic.
  • Route commands with split(" ", 2) and case, and rescue only the errors you expect.
  • Read JSON back with symbolize_names: true, otherwise keys are strings and task[:title] is nil.
  • Write files only in a Dir.mktmpdir folder; with scripted input the output is identical every run.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Mini Project | Thuta Learning