Skip to content

Instantly share code, notes, and snippets.

@jonny-gates
Created October 18, 2019 09:40
Show Gist options
  • Save jonny-gates/fbbdcb47753a7f7aafbe5fa828bd1381 to your computer and use it in GitHub Desktop.
Save jonny-gates/fbbdcb47753a7f7aafbe5fa828bd1381 to your computer and use it in GitHub Desktop.
to-do-manager
class Repository
def initialize
@tasks = []
end
def add(task)
@tasks << task
end
def all
return @tasks
end
def find(task_index)
return @tasks[task_index]
end
end
class Router
def initialize(controller)
@controller = controller
end
def run
loop do
display_choices
choice = ask_user
break if choice == 4
dispatch(choice)
end
end
private
def display_choices
puts 'What do you want to do?'
puts '1. Add a task'
puts '2. List tasks'
puts '3. Mark a task as done'
puts '4. Exit'
end
def ask_user
return gets.chomp.to_i
end
def dispatch(choice)
case choice
when 1
@controller.add_task
when 2
@controller.list_tasks
when 3
@controller.mark_task_as_done
else
puts 'Wrong choice'
end
end
end
class Task
attr_reader :description
def initialize(description)
@done = false
@description = description
end
def mark_as_done!
@done = true
end
def is_done?
return @done
end
end
require_relative 'task'
class TasksController
def initialize(repository, view)
@repository = repository
@view = view
end
def add_task
# 1. Ask the user for a name
description = @view.ask_user_for_description
# 2. Create a task
task = Task.new(description)
# 3. Ask the repo to store it
@repository.add(task)
end
def list_tasks
display_tasks
end
def mark_task_as_done
# 1. Show a list of tasks
display_tasks
# 2. Ask the user which task index
task_index = @view.ask_for_index
# 3. Ask the repo for the task
task = @repository.find(task_index)
# 4. Mark the task as done
task.mark_as_done!
end
private
def display_tasks
# 1. Ask the repo for a list of tasks
tasks = @repository.all
# 2. Ask the view to print out the tasks
@view.list_tasks(tasks)
end
end
class TasksView
def ask_user_for_description
puts 'What do you want to do?'
return gets.chomp
end
# 1. [ ] Not done
# 2. [x] Done
def list_tasks(tasks)
tasks.each_with_index do |task, index|
x = task.is_done? ? '[x]' : '[ ]'
puts "#{index + 1}. #{x} #{task.description}"
end
end
def ask_for_index
puts 'Which task number?'
return gets.chomp.to_i - 1
end
end
require_relative 'task'
require_relative 'repository'
require_relative 'tasks_view'
require_relative 'tasks_controller'
require_relative 'router'
repository = Repository.new
view = TasksView.new
controller = TasksController.new(repository, view)
router = Router.new(controller)
router.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment