-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession_persistence.rb
60 lines (48 loc) · 1.3 KB
/
session_persistence.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class SessionPersistence
def initialize(session)
@session = session
@session[:lists] ||= []
end
def find_list(id)
@session[:lists].find { |l| l[:id] == id }
end
def all_lists
@session[:lists]
end
def create_new_list(list_name)
id = next_element_id(@session[:lists])
@session[:lists] << { id: id, name: list_name, todos: [] }
end
def delete_list(id)
@session[:lists].reject! { |list| list[:id] == id }
end
def update_list_name(id, new_name)
list = find_list(id)
list[:name] = new_name
end
def create_new_todo(list_id, todo_name)
list = find_list(list_id)
id = next_element_id(list[:todos])
list[:todos] << { id: id, name: todo_name, completed: false }
end
def delete_todo_from_list(list_id, todo_id)
list = find_list(list_id)
list[:todos].reject! { |todo| todo[:id] == todo_id }
end
def update_todo_status(list_id, todo_id, new_status)
list = find_list(list_id)
todo = list[:todos].find { |t| t[:id] == todo_id }
todo[:completed] = new_status
end
def mark_all_todos_as_completed(list_id)
list = find_list(list_id)
list[:todos].each do |todo|
todo[:completed] = true
end
end
private
def next_element_id(elements)
max = elements.map { |todo| todo[:id] }.max || 0
max + 1
end
end