class TodosListModel

This module is in charge of interacting with the TODO's database, think of it as a driver

Attributes

current_todos[R]
todos_path[R]

Public Class Methods

new() click to toggle source
# File lib/todos_list_model.rb, line 12
def initialize
  @todos_path = ENV['DATABASE_PATH']
  @current_todos = load_todos
end

Public Instance Methods

add_todo(description) click to toggle source
# File lib/todos_list_model.rb, line 36
def add_todo(description)
  current_todos << TodoModel.new(todos_length + 1, description)
  save_todos
end
completed_todos() click to toggle source
# File lib/todos_list_model.rb, line 32
def completed_todos
  current_todos.select { |todo| todo.status == :completed }
end
delete_pending_todo(index) click to toggle source
# File lib/todos_list_model.rb, line 41
def delete_pending_todo(index)
  index_in_current_todos = @current_todos.index do |todo|
    todo.id == pending_todos[index].id
  end
  @current_todos.delete_at(index_in_current_todos)
  save_todos
end
load_todos() click to toggle source
# File lib/todos_list_model.rb, line 17
def load_todos
  if File.exist?(todos_path)
    file = File.read(todos_path)
    JSON.parse(file).map do |todo|
      TodoModel.new(todo['id'], todo['description'], todo['status'].to_sym)
    end
  else
    []
  end
end
pending_todos() click to toggle source
# File lib/todos_list_model.rb, line 28
def pending_todos
  current_todos.select { |todo| todo.status == :pending }
end
save_todos() click to toggle source
# File lib/todos_list_model.rb, line 49
def save_todos
  File.write(todos_path, current_todos.map(&:as_hash).to_json)
end
todos_length() click to toggle source
# File lib/todos_list_model.rb, line 53
def todos_length
  current_todos.length
end