Thuta Learning
Ruby
ProjectsProgrammingBeginner

Task Tracker Project - Part 3

RubyLesson 3245 min

What you'll walk away with

  • Serialise a tracker to a JSON document (version, next_id, tasks) with to_h and JSON.pretty_generate, and rebuild it with from_h
  • Keep file handling inside one TaskStore class so the model and the Cli never touch a path
  • Write a file atomically, with a temp file and File.rename, so a crash cannot leave half a file behind
  • Validate untrusted data on load and turn JSON::ParserError and bad records into a StoreError that names the problem
  • Explain why next_id is saved and why a pipe-delimited text format breaks on real titles

Explain it simply

Explain it simply

Part 2 works until you close the program, and then every task is gone. Part 3 fixes that by saving the tracker to a file and reading it back at startup, so tomorrow's session starts where today's ended.

The new class, TaskStore, is a librarian. You hand it the whole tracker and it files it away as a JSON document; later it fetches the document and rebuilds the tracker exactly as it was. The rest of the program never learns where the file lives or what it looks like.

Problem → Why → Solution

The problem: one delimited line per task

The quickest way to save a list is one line per task with a separator: "Buy milk|false". It works in a demo and breaks on real data. A title that contains the separator ("Fix | login") splits into three fields on load. Every value comes back as a String, so done is the string "false", which is truthy in Ruby, and every task looks finished. Writing straight into the file also means a crash halfway through leaves a half-written file, and the next start either loses tasks or crashes.

One more trap hides in the ids. If the saved file holds only tasks, the program has to guess the next id. After you delete the newest task and restart, the guess reuses that id, and any old reference to "task 4" now points at a different task.

pipe_format.rb
saved = "Buy milk|false"
title, done = saved.split("|")
puts "finished!" if done                # prints: the String "false" is truthy

risky = "Fix | login bug|false"
p risky.split("|")                     # ["Fix ", " login bug", "false"] - three fields

Why a delimiter format is not enough

A delimiter format has no way to say "this separator is part of the data", and it throws away types: everything is text. JSON was designed for exactly this. Strings are quoted and escaped, numbers and booleans keep their type, and the structure (an object holding a list of objects) is explicit. Ruby ships a JSON parser and generator in its standard library, so the fix costs two method calls.

Core concept: a store that translates between objects and a document

Saving is translation. In memory you have Task objects with behaviour; on disk you have text. TaskStore sits between them and translates in both directions, and the rules about what a valid file looks like are checked on the way back in, because a file is input from outside the program even when your own program wrote it yesterday.

1. Choose a document shape and write it down

The file is one JSON object with three keys: version (1, so a later format can be recognised), next_id (the counter, so ids are never reused) and tasks (a list of objects with id, title, priority and done). Task#to_h from Part 1 already produces one entry, and TaskTracker#to_h wraps them together.

2. Generate with pretty_generate

JSON.pretty_generate(hash) returns indented text that a person can read and a diff tool can compare. Strings are escaped correctly, including quotes and non-ASCII text such as Myanmar, which is written as UTF-8 characters.

3. Rebuild through the same validation

Task.from_h and TaskTracker.from_h read the parsed Hash and call the normal constructors, so a record in the file passes through exactly the rules a new task does. The TaskTracker constructor also sets @next_id to the larger of the saved value and the highest id plus one, so a hand-edited file cannot cause duplicate ids.

4. Wrap every failure in one error class

A missing file is normal: the first run starts with an empty tracker. A damaged file is not. TaskStore#load rescues JSON::ParserError and ArgumentError and raises StoreError with a message that names the file (without its full path) and the problem. The caller has one class to handle and never sees a stack trace from inside the JSON library.

5. Write atomically

save writes tasks.json.tmp first and then File.rename moves it over tasks.json. On most systems the rename replaces the old file in one step, so a crash leaves either the complete old file or the complete new one, never half of each.

6. Save after each successful change

Cli takes an optional store and calls save after add, done and delete. Saving only on exit loses everything on a crash or Ctrl-C; saving after each change costs a few milliseconds for a list this size.

FailureWhere it is caughtWhat the user sees
File missingTaskStore#load (File.exist?)An empty tracker, no error
Broken JSONrescue JSON::ParserErrorStoreError: tasks.json is not valid JSON
Bad record (unknown priority, missing title)Task constructor via from_hStoreError: tasks.json: task number 1: ...
Typo in a commandCli's rescueAn Error: ... reply, nothing saved
Mental model: a librarian with a strict intake desk
  1. Tracker -> Hash with to_h
  2. Hash -> JSON text with pretty_generate
  3. Write temp file, rename over the real one
  4. Read back: parse, validate, rebuild

Everything that comes from the file is untrusted until it has passed through the same constructors as a brand-new task.

General pattern

ruby
def load(path)
  return Collection.new unless File.exist?(path)
  Collection.from_h(JSON.parse(File.read(path)))
end

def save(path, collection)
  File.write("#{path}.tmp", JSON.pretty_generate(collection.to_h))
  File.rename("#{path}.tmp", path)
end

load returns an empty collection when there is no file, otherwise it parses and rebuilds with from_h. save writes a temp file first and replaces the real one with a rename.

Part 3 code: a TaskStore and a persistent Cli

The file is again complete. Part 3 adds a StoreError, Task.from_h, a TaskTracker constructor that accepts saved tasks, to_h and from_h on the tracker, the TaskStore class, and a store: option on Cli. The demo runs everything inside Dir.mktmpdir, so no file stays behind on your disk and the output never contains a path. It simulates two program runs and then damages the file on purpose.

task_tracker.rb
require "json"
require "tmpdir"

class TaskNotFound < StandardError
  def initialize(id)
    super("no task with id #{id}")
  end
end

# New in Part 3: one error class for everything that can go wrong with the file.
class StoreError < StandardError; end

class Task
  PRIORITIES = %i[low medium high].freeze

  attr_reader :id, :title, :priority

  def initialize(id:, title:, priority: :medium, done: false)
    unless id.is_a?(Integer) && id.positive?
      raise ArgumentError, "id must be a positive integer"
    end

    clean = title.to_s.strip
    raise ArgumentError, "title can't be blank" if clean.empty?
    unless PRIORITIES.include?(priority)
      allowed = PRIORITIES.inspect
      raise ArgumentError, "priority must be one of #{allowed}, got #{priority.inspect}"
    end
    raise ArgumentError, "done must be true or false" unless [true, false].include?(done)

    @id = id
    @title = clean
    @priority = priority
    @done = done
  end

  # New in Part 3: rebuild a Task from the Hash that JSON.parse produced.
  def self.from_h(hash)
    raise ArgumentError, "a task must be a JSON object" unless hash.is_a?(Hash)

    new(id: hash["id"], title: hash["title"],
        priority: hash["priority"].to_s.to_sym, done: hash["done"])
  end

  def done? = @done

  def complete!
    @done = true
    self
  end

  def to_h
    { "id" => id, "title" => title, "priority" => priority.to_s, "done" => done? }
  end

  def to_s
    "##{id} [#{done? ? "x" : " "}] #{title} (#{priority})"
  end
end

class TaskTracker
  include Enumerable

  # New in Part 3: a tracker can start from tasks that were saved earlier.
  def initialize(tasks: [], next_id: 1)
    ids = tasks.map(&:id)
    raise ArgumentError, "duplicate task ids" if ids.uniq.size != ids.size

    @tasks = tasks.dup
    @next_id = [next_id, (ids.max || 0) + 1].max
  end

  # New in Part 3: rebuild a tracker from the parsed document.
  def self.from_h(data)
    unless data.is_a?(Hash) && data["tasks"].is_a?(Array)
      raise ArgumentError, 'expected an object with a "tasks" array'
    end

    tasks = data["tasks"].each_with_index.map do |record, index|
      Task.from_h(record)
    rescue ArgumentError => e
      raise ArgumentError, "task number #{index + 1}: #{e.message}"
    end
    new(tasks: tasks, next_id: data["next_id"].is_a?(Integer) ? data["next_id"] : 1)
  end

  # New in Part 3: the document shape that goes into tasks.json.
  def to_h
    { "version" => 1, "next_id" => @next_id, "tasks" => @tasks.map(&:to_h) }
  end

  def add(title, priority: :medium)
    task = Task.new(id: @next_id, title: title, priority: priority)
    @tasks << task
    @next_id += 1
    task
  end

  def each(&block)
    return enum_for(:each) unless block

    @tasks.each(&block)
    self
  end

  def size = @tasks.size
  def empty? = @tasks.empty?

  def fetch(id)
    @tasks.find { |task| task.id == id } || raise(TaskNotFound, id)
  end

  def complete(id) = fetch(id).complete!

  def remove(id)
    task = fetch(id)
    @tasks.delete(task)
    task
  end

  def pending = reject(&:done?)
end

# New in Part 3: all file handling lives here, behind load and save.
class TaskStore
  def initialize(path)
    @path = path
  end

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

    TaskTracker.from_h(JSON.parse(File.read(@path)))
  rescue JSON::ParserError
    raise StoreError, "#{File.basename(@path)} is not valid JSON"
  rescue ArgumentError => e
    raise StoreError, "#{File.basename(@path)}: #{e.message}"
  end

  def save(tracker)
    temp = "#{@path}.tmp"
    File.write(temp, JSON.pretty_generate(tracker.to_h))
    File.rename(temp, @path)
  end
end

class Cli
  HELP = "commands: add <title> [!low|!medium|!high], list, done <id>, delete <id>"
  CHANGING = %w[add done delete].freeze

  # New in Part 3: an optional store that is saved after every successful change.
  def initialize(tracker, store: nil)
    @tracker = tracker
    @store = store
  end

  def execute(line)
    command, arg = line.strip.split(/\s+/, 2)
    reply = case command
            when "add"    then add(arg)
            when "list"   then list
            when "done"   then "Completed #{@tracker.complete(parse_id(arg))}"
            when "delete" then "Deleted #{@tracker.remove(parse_id(arg))}"
            when nil      then HELP
            else "Unknown command #{command.inspect}. #{HELP}"
            end
    @store.save(@tracker) if @store && CHANGING.include?(command)
    reply
  rescue TaskNotFound, ArgumentError => e
    "Error: #{e.message}"
  end

  private

  def add(arg)
    title, flag = arg.to_s.match(/\A(.*?)(?:\s+!(\w+))?\z/).captures
    priority = flag ? flag.to_sym : :medium
    "Added #{@tracker.add(title, priority: priority)}"
  end

  def list
    return "No tasks yet." if @tracker.empty?

    lines = @tracker.map(&:to_s)
    lines << "#{@tracker.pending.size} of #{@tracker.size} pending"
    lines.join("\n")
  end

  def parse_id(text)
    id = Integer(text.to_s, 10, exception: false)
    id || raise(ArgumentError, "expected a task id, got #{text.inspect}")
  end
end

def session(title, cli, commands)
  puts "== #{title} =="
  commands.each do |command|
    puts "> #{command}"
    puts cli.execute(command)
  end
end

# The demo works inside a temporary folder that is deleted when the block ends.
Dir.mktmpdir("task-tracker") do |dir|
  path = File.join(dir, "tasks.json")
  store = TaskStore.new(path)

  session("first run (no file yet)", Cli.new(store.load, store: store), [
    "add Buy milk !high",
    "add မနက်ဖြန် အစည်းအဝေး",
    "add Write tests !low",
    "done 2",
    "delete 3",
  ])
  puts "-- tasks.json --"
  puts File.read(path)

  session("second run (loaded from disk)", Cli.new(store.load, store: store), [
    "list",
    "add Review notes",
  ])

  File.write(path, '{"tasks": [')
  begin
    store.load
  rescue StoreError => e
    puts "== damaged file ==", "Error: #{e.message}"
  end

  bad = { "id" => 1, "title" => "Ship it", "priority" => "urgent", "done" => false }
  File.write(path, JSON.generate({ "tasks" => [bad] }))
  begin
    store.load
  rescue StoreError => e
    puts "Error: #{e.message}"
  end
end

Code breakdown

  1. A next id that can never go backwards@next_id = [next_id, (ids.max || 0) + 1].max

    It takes the larger of the saved next_id and "highest id + 1". Even if the file's next_id is too low it is corrected, and (ids.max || 0) makes an empty list start from 0, which gives 1.

  2. Rebuild every record through TaskTask.from_h(record)

    Each record goes through Task.new, so an unknown priority, a missing title or a done flag stored as text is refused. The rescue adds the record number, which is why the message begins "task number 1: ...".

  3. Wrap parse failuresrescue JSON::ParserError

    JSON.parse rejects broken text with JSON::ParserError. This rescue converts it into your own StoreError, and File.basename keeps the full path out of the message you wrote.

  4. Replace the file in one stepFile.rename(temp, @path)

    The temp file is written completely before the rename. If anything fails before this line, the previous tasks.json is untouched.

  5. Save only after success@store.save(@tracker) if @store && CHANGING.include?(command)

    When a command raises, execution never reaches this line, so a failed command does not touch the file. Read-only commands such as list are not in CHANGING and are not saved either.

  6. A temporary folder for the demoDir.mktmpdir("task-tracker") do |dir|

    When the block ends the folder is deleted together with its contents. This is the pattern for testing a store without ever touching your real data file.

  7. UTF-8 stays readableputs File.read(path)

    Look at "မနက်ဖြန် အစည်းအဝေး" in the output: it is stored as readable Myanmar text, not as escape sequences such as \u1019. Ruby's default encoding is UTF-8, so nothing is lost between write and read.

You should see
== first run (no file yet) ==
> add Buy milk !high
Added #1 [ ] Buy milk (high)
> add မနက်ဖြန် အစည်းအဝေး
Added #2 [ ] မနက်ဖြန် အစည်းအဝေး (medium)
> add Write tests !low
Added #3 [ ] Write tests (low)
> done 2
Completed #2 [x] မနက်ဖြန် အစည်းအဝေး (medium)
> delete 3
Deleted #3 [ ] Write tests (low)
-- tasks.json --
{
  "version": 1,
  "next_id": 4,
  "tasks": [
    {
      "id": 1,
      "title": "Buy milk",
      "priority": "high",
      "done": false
    },
    {
      "id": 2,
      "title": "မနက်ဖြန် အစည်းအဝေး",
      "priority": "medium",
      "done": true
    }
  ]
}
== second run (loaded from disk) ==
> list
#1 [ ] Buy milk (high)
#2 [x] မနက်ဖြန် အစည်းအဝေး (medium)
1 of 2 pending
> add Review notes
Added #4 [ ] Review notes (medium)
== damaged file ==
Error: tasks.json is not valid JSON
Error: tasks.json: task number 1: priority must be one of [:low, :medium, :high], got :urgent
Life of one saved change
  1. Cli runs a changing command
  2. The tracker changes in memory
  3. store.save builds the JSON text
  4. The text goes into tasks.json.tmp
  5. File.rename replaces tasks.json

The command succeeds

The file always holds a complete document

The command raises

save is never reached, the file is untouched

Reading JSON back: strings, not symbols

JSON.parse returns Hash keys as Strings by default, which is why from_h reads hash["id"]. The symbolize_names: true option gives Symbol keys when you prefer them. The more important point is Symbol values. JSON has no symbols, so :high is written as "high" and reading it back gives the String "high". Because Task insists on a Symbol priority, from_h has to convert with hash["priority"].to_s.to_sym.

json_types.rb
require "json"

text = '{"id": 1, "done": false, "title": null}'
data = JSON.parse(text)
p data                                      # keys come back as Strings
p data["done"], data["title"]               # real false and nil, not text
p JSON.parse(text, symbolize_names: true)   # an option when you prefer Symbol keys

puts JSON.generate({ id: 1, priority: :high })    # a Symbol is written as a String
p JSON.parse(JSON.generate({ priority: :high }))["priority"]

Booleans and null come back exactly: false is false and null is nil, which is the main reason the pipe format was rejected. The hashes are shown in Ruby 4.0.9's print format, so on Ruby 3.3 and earlier you will see {"id"=>1} instead.

The limits of a JSON file

A JSON file is a good fit for a personal tool, but it has limits. If two trackers run at once and each saves without knowing about the other's changes, the last writer wins. Every save rewrites the whole list, which slows down once you have thousands of tasks, and there is no history. Advisory locks such as File#flock exist, but at that point a database like SQLite is usually the better tool. You can keep the load and save interface of TaskStore and change only its insides.

In real projects

In real projects

Config files, editor settings, package manifests (package.json, Gemfile.lock), saved game state and small CLI tools like todo managers all use this pattern: a versioned JSON document, loaded at startup and saved after a change. The version field is what lets a later release say "this is a version 1 file, convert it before use". next_id is the same idea as a database sequence: the counter has to be stored because it cannot be recomputed once rows have been deleted.

Atomic replacement matters in real tools. Editors and package managers write a temp file and rename it, because users do press Ctrl-C and machines do lose power. For data that more than one process updates, or that keeps growing, the next step is a database such as SQLite, which gives you transactions and locking. The TaskStore interface (load and save) is what you would keep, and only its insides change.

Common mistakes

Common mistakes

Trusting the file because your program wrote it

Users edit files, older versions write different shapes, and disks get corrupted. Treat load as untrusted input and run every record through the normal constructors. Without validation, one record with priority "urgent" spreads through the rest of the program.

Overwriting the file directly

File.write(path, ...) empties the old file the moment it opens it. If the process dies or you press Ctrl-C while writing, only a half-written file remains and the old data cannot be recovered. Write a temp file and replace the real one with File.rename.

Silently replacing a damaged file with an empty tracker

If you rescue and return TaskTracker.new, the program starts normally, but the user's first add then saves over a damaged file that might have been recoverable, replacing it with a file holding one task. Raise StoreError and let the user decide.

Forgetting that JSON turns symbols into strings

Save priority: :high and read it back and you get the String "high"; Task accepts only Symbols, so Task.new refuses it. from_h has to convert, or every saved file fails to load with a message about priority and "high".

Mini challenge

Read both file formats

Suppose version 0 of the tracker saved a bare JSON array of task Hashes, with no version and no next_id. Write load_snapshot(path) that returns a Hash in the version 1 shape for either file: for an array, wrap it and compute next_id as the highest id plus one (1 for an empty list). A missing file returns an empty snapshot. Anything that is not an array, or an object with a tasks array, raises a StoreError.

  • A missing file gives {"version" => 1, "next_id" => 1, "tasks" => []}
  • A bare array is wrapped, and next_id is the highest id + 1 (or 1 for an empty array)
  • An object keeps its own next_id, but never lower than the highest id + 1
  • Invalid JSON, or JSON of any other shape, raises StoreError with a message
load_snapshot.rb
require "json"

class StoreError < StandardError; end

def load_snapshot(path)
  # TODO: a missing file returns an empty version-1 snapshot
  # TODO: parse the JSON and wrap JSON::ParserError in a StoreError
  # TODO: a bare Array is a version-0 file: wrap it as { "tasks" => array }
  # TODO: the result needs a "tasks" Array of Hashes, otherwise raise StoreError
  # TODO: next_id is never lower than the highest id + 1
end

Expected: One line for each of seven files: next_id=1 for the missing file and the empty array, next_id=8 for v0.json, 6 for v1-low, 40 for v1-high, and one StoreError message each for broken.json and number.json.

Show hint

Check File.exist? first. Collect the ids with filter_map and skip anything that is not an Integer. [saved, highest + 1].max keeps next_id from being too low. A rescue JSON::ParserError can sit at the end of the whole method.

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

class StoreError < StandardError; end

# Reads a version-0 file (a bare Array) or a version-1 file (an object) and
# always returns the version-1 shape.
def load_snapshot(path)
  return { "version" => 1, "next_id" => 1, "tasks" => [] } unless File.exist?(path)

  data = JSON.parse(File.read(path))
  data = { "tasks" => data } if data.is_a?(Array)
  unless data.is_a?(Hash) && data["tasks"].is_a?(Array) && data["tasks"].all?(Hash)
    raise StoreError, "#{File.basename(path)} has an unknown shape"
  end

  ids = data["tasks"].filter_map { |task| task["id"] if task["id"].is_a?(Integer) }
  saved = data["next_id"].is_a?(Integer) ? data["next_id"] : 1
  next_id = [saved, (ids.max || 0) + 1].max
  { "version" => 1, "next_id" => next_id, "tasks" => data["tasks"] }
rescue JSON::ParserError
  raise StoreError, "#{File.basename(path)} is not valid JSON"
end

cases = {
  "missing.json" => nil,
  "v0-empty.json" => "[]",
  "v0.json" => '[{"id": 3, "title": "Old task"}, {"id": 7, "title": "Older task"}]',
  "v1-low.json" => '{"version": 1, "next_id": 2, "tasks": [{"id": 5}]}',
  "v1-high.json" => '{"version": 1, "next_id": 40, "tasks": [{"id": 5}]}',
  "broken.json" => '{"tasks": [',
  "number.json" => "42",
}

Dir.mktmpdir("snapshots") do |dir|
  cases.each do |name, content|
    path = File.join(dir, name)
    File.write(path, content) if content

    begin
      snapshot = load_snapshot(path)
      puts "#{name}: next_id=#{snapshot["next_id"]} tasks=#{snapshot["tasks"].size}"
    rescue StoreError => e
      puts "#{name}: StoreError - #{e.message}"
    end
  end
end

Quick quiz 1 / 3

Why does JSON round-trip a task's done flag more safely than a "title|false" line?

Quick quiz 2 / 3

Why does the store write tasks.json.tmp and then call File.rename?

Quick quiz 3 / 3

The saved file says "next_id": 4 but its highest task id is 9 because someone edited it. What is @next_id after loading?

What to remember

  • Delimiter formats break on titles that contain the separator and lose types, so use a versioned JSON document
  • TaskStore keeps load and save in one place, so the model and the Cli never know a path
  • Treat data from the file as untrusted: run it through the normal constructors and report problems as StoreError
  • Writing a temp file and replacing with File.rename leaves no half-written file after a crash
  • Save next_id and never let it fall below the highest id + 1, so ids are not reused

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.

Task Tracker Project - Part 3 | Thuta Learning