Skip to content

Instantly share code, notes, and snippets.

@scottswezey
Created August 6, 2010 23:23
Show Gist options
  • Save scottswezey/512185 to your computer and use it in GitHub Desktop.
Save scottswezey/512185 to your computer and use it in GitHub Desktop.
class TodoList
attr_accessor :file
def load(file = 'todo.txt')
@file = file
@list = []
# Check that file exists
if using_valid_file?
# read the file, create a list, create items, add them
File.readlines(@file, "\n").each do |item|
add(item)
end
end
end
def initialize(file)
@list = []
load(file)
end
def add(item)
@list << TodoItem.new(item)
end
def write
# raise "File(#{@file}) is not writeable." unless using_valid_file?
# write the file, only write the undone items
File.open(@file, "w") do |f|
f.write @list.reject(&:done?).join("\n")
end
end
def [](id)
@list[id]
end
def to_s
ret_val = ""
@list.each_index do |i|
ret_val << "Item #{i}: '#{@list[i]}' is #{@list[i].done? ? 'done' : 'not done'}.\n"
end
return ret_val #I know return isn't needed... but I hate not having it, lol.
end
private
def using_valid_file?
File.writable?(@file)
end
end
class TodoItem
# provide reader and setter for name and state
attr_accessor :name, :state
alias_method :done?, :state
def initialize(name)
# store name
@name = name
# set state to undone
@state = false
end
def to_s
@name
end
end
# ---
# the library will be used like this:
# list = TodoList.load("todo.td")
# list[0].done = true
# list.add "another cool item"
# list.write
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment