Skip to content

Instantly share code, notes, and snippets.

@jonny-gates
Created January 24, 2020 10:45
Show Gist options
  • Save jonny-gates/ce4151f3676ddf7f9177fe2788047b6d to your computer and use it in GitHub Desktop.
Save jonny-gates/ce4151f3676ddf7f9177fe2788047b6d to your computer and use it in GitHub Desktop.
ToDo Manager
require_relative 'view'
require_relative 'repo'
require_relative 'controller'
require_relative 'router'
view = View.new
repo = Repo.new
controller = Controller.new(view, repo)
router = Router.new(controller)
router.run
require_relative 'task'
class Controller
def initialize(view, repo)
@view = view
@repo = repo
end
def add_task
# 1. Ask the user for a title
title = @view.ask_for_title
# 2. Create a task
task = Task.new(title)
# 3. Add the task to the repo
@repo.add(task)
end
def list_tasks
# 1. Ask the repo for the tasks
tasks = @repo.all_tasks
# 2. Ask the view to display
@view.list_tasks(tasks)
end
def mark_task_as_complete
# 1. Show the list of tasks
list_tasks
# 2. Ask the user which task
index = @view.ask_for_index
# 3. Get the task from the repo
task = @repo.find_task(index)
# 4. Mark the task complete
task.mark_as_complete!
end
def delete_task
# 1. List tasks
list_tasks
# 2. Ask the user which task
index = @view.ask_for_index
# 3. Ask the repo to remove the task
@repo.delete(index)
end
end
class Repo
# CRUD
def initialize
@tasks = [] # Class objects
end
def add(task)
@tasks << task
end
def all_tasks
return @tasks
end
def find_task(index)
return @tasks[index]
end
def delete(index)
@tasks.delete_at(index)
end
end
class Router
def initialize(controller)
@controller = controller
end
def run
loop do
puts "What do you want to do?"
puts "1. Add task"
puts "2. List tasks"
puts "3. Mark task done"
puts "4. Delete a task"
puts "10. Exit"
answer = gets.chomp.to_i
case answer
when 1 then @controller.add_task
when 2 then @controller.list_tasks
when 3 then @controller.mark_task_as_complete
when 4 then @controller.delete_task
when 10 then break
else
puts 'Pick again!'
end
end
end
end
require_relative 'repo'
class Task
attr_reader :title
def initialize(title)
@title = title
@done = false
end
def mark_as_complete!
@done = true
end
def done?
return @done
end
end
# task1 = Task.new('Do laundry')
# task2 = Task.new('Get beer')
# repo = Repo.new
# repo.add(task1)
# repo.add(task2)
# p repo
class View
def ask_for_title
puts "What do you want to do?"
return gets.chomp
end
def list_tasks(tasks)
tasks.each_with_index do |task, index|
x = task.done? ? 'x' : ' '
puts "#{index + 1}. [#{x}] #{task.title}"
end
end
def ask_for_index
puts 'Which task number?'
return gets.chomp.to_i - 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment