Created
April 3, 2013 14:29
-
-
Save moritzschaefer/5301705 to your computer and use it in GitHub Desktop.
Small TODO Script in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'debugger' | |
| TODO_FILE = "#{Dir.home}/.mtodo" | |
| COMMANDS = [:list, :remove, :add, :help] | |
| class Todo | |
| attr_reader :todolist | |
| def initialize(todofile) | |
| @todofile = todofile | |
| @todolist = read | |
| end | |
| def remove(index) | |
| @todolist.delete_at(index) | |
| end | |
| def add(content) | |
| @todolist.push content | |
| end | |
| def save | |
| begin | |
| File.open @todofile, 'w' do |file| | |
| file.write @todolist.join "\n" | |
| end | |
| rescue | |
| print "Could not save file\n" | |
| end | |
| end | |
| # flush on destructor | |
| private | |
| def read | |
| begin | |
| File.open @todofile do |file| | |
| @todolist = file.each_line.collect { |x| x.delete "\n" } | |
| end | |
| rescue | |
| print "Could't open/read file\n" | |
| @todolist = [] | |
| end | |
| end | |
| end | |
| class Manager | |
| def initialize | |
| @todo = Todo.new(TODO_FILE) | |
| end | |
| def list | |
| i = 1 | |
| @todo.todolist.each do |todo| | |
| print i.to_s + ": " + todo + "\n" | |
| i+=1 | |
| end | |
| end | |
| def add | |
| begin | |
| @todo.add(ARGV[1]) | |
| rescue | |
| print "Needs some argument to add.\n" | |
| end | |
| end | |
| def remove | |
| index = ARGV[1].to_i | |
| if index == 0 | |
| print "Give a valid index\n" | |
| else | |
| @todo.remove index-1 | |
| end | |
| end | |
| def help | |
| print "Available commands: " + COMMANDS.map{ |s| s.to_s}.join(' ') + "\n" | |
| end | |
| def save | |
| @todo.save | |
| end | |
| end | |
| manager = Manager.new | |
| if ARGV.length > 0 | |
| command = ARGV[0].to_sym | |
| if COMMANDS.include? command | |
| manager.send(command) | |
| manager.save | |
| else | |
| manager.help | |
| end | |
| else | |
| manager.help | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment