Skip to content

Instantly share code, notes, and snippets.

@Martin-Alexander
Created July 19, 2019 15:46
Show Gist options
  • Save Martin-Alexander/8bff68404d0e8a748fee779ad8630f45 to your computer and use it in GitHub Desktop.
Save Martin-Alexander/8bff68404d0e8a748fee779ad8630f45 to your computer and use it in GitHub Desktop.
require_relative "task"
require_relative "repository"
require_relative "view"
require_relative "controller"
require_relative "router"
repository = Repository.new
view = View.new
controller = Controller.new(view, repository)
router = Router.new(controller)
router.run
# Role: Coordinate with the view and repo to fulfill user actions
class Controller
def initialize(view, repository)
@view = view # instance of View
@repository = repository # instance of Repository
end
# User action: create a new task
def create_task
task_name = @view.ask_for_name
task = Task.new(task_name)
@repository.add_task(task)
end
# User action: display all tasks
def list
# repo: give me all the tasks
tasks = @repository.all
# view: take these tasks and display them
@view.display_tasks(tasks)
end
# User action: mark a task as done
def mark_as_done
# view: ask for specific task index
task_index = @view.ask_for_task_index
# repo: get the task belonging to that index
task = @repository.find(task_index)
# mark the task as done
task.mark_as_done!
end
end
# Role: To store and retrieve tasks
class Repository
def initialize
@tasks = [] # An array of Task instances (not Strings or Hashes or etc...)
# go to csv and load up tasks
end
def add_task(new_task)
@tasks << new_task
# save to the csv file
end
def all
return @tasks
end
def find(index)
return @tasks[index]
end
end
# Role: Ask the user what action they'd like to do, and in turn tell the controller
class Router
def initialize(controller)
@controller = controller
end
def run
puts "Welcome to TODO!"
loop do
puts "What would you like to do?"
puts "1 - New Task"
puts "2 - List"
puts "3 - Mark as done"
puts "4 - Quit"
user_input = gets.chomp.to_i
if user_input == 1
@controller.create_task
elsif user_input == 2
@controller.list
elsif user_input == 3
@controller.mark_as_done
elsif user_input == 4
break
else
puts "Invalid input"
end
end
end
end
# Role: Represent each task in our todo/task-manager
class Task
attr_reader :name, :done
def initialize(name)
@name = name
@done = false
end
def mark_as_done!
@done = true
end
end
# Role: Interact with the user: recieve info (gets) and display info (puts)\
class View
def ask_for_name
puts "Enter task name:"
task_name = gets.chomp
return task_name
end
def display_tasks(tasks)
tasks.each_with_index do |task, index|
if task.done
puts " #{index} - [X] #{task.name}"
else
puts " #{index} - [ ] #{task.name}"
end
end
end
def ask_for_task_index
puts "Enter task index:"
task_index = gets.chomp.to_i
return task_index
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment