Skip to Content
Course content

35: Building a Simple File-Based Task Tracker

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When you first start building apps that actually save data, you'll likely run into a frustrating wall the moment you try to load your data. I remember doing this early on: I'd spend an hour writing a beautiful logic system, hit "run," and immediately get a crash before the program even started. Here is a piece of code that looks perfectly reasonable, but it's a trap.

def load_tasks
  File.readlines("tasks.txt").map { |line| line.chomp }
end

tasks = load_tasks
puts "Your tasks: #{tasks}"

The 'Missing File' Crash

If you run that code on a fresh machine, Ruby will throw an Errno::ENOENT (No such file or directory @ rb_sysopen - tasks.txt). The problem is that File.readlines assumes the file already exists. It doesn't say, "Oh, I don't see a file here, I'll just return an empty list." It just panics and dies.

Handling the Initial Run

To fix this, we need to be defensive. We should check if the file exists before we try to read it. If it doesn't, we simply return an empty array. This allows the program to boot up normally the first time a user runs it, and then it will work as expected once the program creates the file for the first time.

def load_tasks
  return [] unless File.exist?("tasks.txt")
  
  File.readlines("tasks.txt").map { |line| line.chomp }
end

Now, let's build this out into a proper tracker. We want something that doesn't just read and write, but manages the state of our tasks during a session.

Structuring the Task Logic

I find it's much cleaner to wrap this in a class. It keeps our file-handling logic separate from the user interface. We'll use a simple array of strings for this version, but in a real-world app, you'd likely use an array of objects or a CSV.

class TaskTracker
  FILE_NAME = "tasks.txt"

  def initialize
    @tasks = load_tasks
  end

  def add(task_text)
    @tasks << task_text
    save_tasks
  end

  def list
    @tasks.each_with_index { |task, i| puts "#{i + 1}. #{task}" }
  end

  def remove(index)
    @tasks.delete_at(index - 1)
    save_tasks
  end

  private

  def load_tasks
    return [] unless File.exist?(FILE_NAME)
    File.readlines(FILE_NAME).map { |line| line.chomp }
  end

  def save_tasks
    File.open(FILE_NAME, "w") do |file|
      file.puts @tasks
    end
  end
end

Persisting Tasks to Disk

Notice the save_tasks method. I used File.open(FILE_NAME, "w"). The "w" flag is crucial here—it tells Ruby to truncate the file (wipe it clean) before writing. If we used "a" (append), every time we saved our list, we'd just keep adding the entire list to the end of the file, creating a massive, redundant mess.

The block syntax do |file| ... end is the professional way to handle files. It ensures that the file is closed automatically even if an error occurs inside the block. Manually calling file.close is a habit you should break early; it's too easy to forget, and leaking file descriptors is a great way to crash a production server.

To tie it all together, you'd just need a simple loop in your main script to call these methods based on user input. You've now moved from "volatile" memory (where data disappears when the program stops) to "persistent" storage.




📋 Practical Task

Implementing a Task Completion Toggle

Modify the TaskTracker class provided in the lesson to support "completed" tasks. Since we are using a simple text file, you can't just store a boolean. You'll need to change how tasks are stored in the file.

  • The Requirement: Tasks should be stored in the format "[ ] Task name" for incomplete tasks and "[x] Task name" for completed ones.
  • The Method: Add a method called toggle_task(index) that finds the task at the given index and switches its status between [ ] and [x].
  • The Update: Update the add method so that every new task starts with the "[ ] " prefix.
  • The Logic: Ensure that when save_tasks is called, the updated prefixes are written correctly to the file.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.