Last active
December 12, 2015 08:19
-
-
Save kmandreza/4743420 to your computer and use it in GitHub Desktop.
Ruby Todos 1.0: Core Features
This file contains 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
require_relative 'view' | |
require_relative 'FileReadWrite' | |
class Parser | |
TODO_FILE = 'Todolist.txt' | |
def initialize(user_input) | |
@filerw = FileReadWrite.new(TODO_FILE) | |
@list = get_list | |
@viewer = Viewer.new | |
parse(user_input) | |
end | |
def add(list_item) | |
@list.push("#{@list.length + 1}. [ ] #{list_item}") | |
@viewer.add_message(list_item) | |
display | |
reorder | |
write | |
end | |
def delete(index) | |
deleted_item = @list.delete_at(index) | |
@viewer.delete_message(text_cleanup(deleted_item)) | |
reorder | |
display | |
write | |
end | |
def list(user_input) | |
display | |
end | |
def complete(index) | |
@list[index].sub!("[ ]", "[x]") | |
display | |
write | |
end | |
private | |
def parse(user_input) | |
case user_input.first | |
when "list" then list user_input[1..-1] | |
when "add" then add user_input[1..-1].join(" ") | |
when "delete" then delete (user_input[1].to_i - 1) | |
when "complete" then complete (user_input[1].to_i - 1) | |
else @viewer.error_message | |
end | |
end | |
def write | |
@filerw.write_file(@list) | |
end | |
def get_list | |
@filerw.read_file | |
end | |
def reorder | |
@list.each_with_index do |list_item, index| | |
list_item.sub!(/\d+/, "#{index + 1}") | |
end | |
end | |
def display | |
@viewer.display(@list) | |
end | |
def text_cleanup(text) | |
text.sub(/^\d*.\s*\W\s\W/, "") | |
end | |
end | |
This file contains 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
class FileReadWrite | |
def initialize(filename) | |
@filename = filename | |
end | |
def read_file | |
File.open(@filename).readlines | |
end | |
def write_file(list_items) | |
File.open(@filename, 'w') do |f| | |
list_items.each { |list_item| f.write(list_item)} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment