Skip to content

Instantly share code, notes, and snippets.

@bouk
Created October 23, 2012 15:47
Show Gist options
  • Save bouk/3939575 to your computer and use it in GitHub Desktop.
Save bouk/3939575 to your computer and use it in GitHub Desktop.
Proper todo list!
# encoding: UTF-8
module BoukeTodoApp
class TodoList
def initialize(filename)
@items = []
@filename = filename
self.load
end
def print
@items.each do |item|
puts item
end
end
def each
@items.each { |item| yield item }
end
def cli(argv)
if argv.size == 0
self.print
else
command = argv[0]
arguments = argv[1, argv.size - 1]
case command
when 'list'
self.print
when 'add'
if arguments.size == 0
puts %(USAGE: #{$0} add "todo list item")
else
arguments.each { |contents|
self.add contents
}
end
when 'remove'
if arguments.size == 0
puts %(USAGE: #{$0} remove "todo list item")
else
arguments.each { |contents|
self.remove contents
}
end
when 'done'
if arguments.size == 0
puts %(USAGE: #{$0} done "todo list item")
else
arguments.each { |contents|
self.done contents
}
end
else
puts "Unknown action"
end
end
end
def add(contents)
@items << Item.new(contents, false)
end
def remove(contents)
@items.delete_if { |item| item.contents == contents }
end
def done(contents)
@items.find_all { |item| item.contents == contents }.each { |item| item.done = true }
end
def load
if File.exists? @filename
File.open(@filename) do |f|
lines = f.read().split("\n").map! { |item| [item[0], item[1, item.size - 1]] }
lines.each do |done, contents|
@items << Item.new(contents, done.to_i == 1) if done and contents
end
end
end
end
def save
File.open(@filename, 'w') do |f|
@items.each { |item|
f.write(item.done ? "1" : "0")
f.write(item.contents)
f.write("\n")
}
end
end
class Item
attr_accessor :done, :contents
def initialize(contents, done=false)
@contents = contents
@done = done
end
def to_s
(@done ? "✓" : "✗") + " " + @contents
end
end
end
end
if __FILE__ == $0
todo_list = BoukeTodoApp::TodoList.new("list.todo")
todo_list.cli(ARGV)
todo_list.save
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment