-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodo.rb
93 lines (80 loc) · 1.79 KB
/
todo.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
require 'sinatra'
require 'data_mapper'
if ENV['RACK_ENV'] != "production"
require 'sqlite3'
require 'dotenv'
Dotenv.load '.env'
DataMapper.setup(:default, "sqlite:todo.db")
end
if ENV['RACK_ENV'] == "production"
DataMapper.setup(:default, ENV['DATABASE_URL'])
end
# Todo model
class Todo
include DataMapper::Resource
property :id, Serial
property :title, Text
property :description, Text
property :created_at, DateTime
# property :due_by, DateTime
end
DataMapper.finalize
DataMapper.auto_upgrade!
def show_params(params)
puts "\n"
p params
puts "\n"
end
# Root endpoint calls all todos in database and sends response to primary list page.
get "/" do
@todos = Todo.all
erb :todo_list
end
# Need a get method to call an erb file containing the code for the second form.
get "/todos/new" do
show_params(params)
@todo = Todo.new
# We're going to create a new todo and call the erb method to bring up the new_todo form.
erb :new_todo
end
post "/todos" do
show_params(params)
todo_attributes = params["todo"]
todo_attributes["created_at"] = DateTime.now
@todo = Todo.create(todo_attributes)
if @todo.save
redirect "/"
else
erb :new_todo
end
end
get "/todos/:id" do
show_params(params)
todo_id = params[:id]
@todo = Todo.get(todo_id)
erb :todo_description
end
get "/todos/:id/update" do
show_params(params)
todo_id = params[:id]
@todo = Todo.get(todo_id)
erb :todo_update
end
put "/todos/:id/update" do
show_params(params)
todo_update = params[:id]
@todo = Todo.get(todo_update)
@todo.update(params["todo"])
if @todo.saved?
redirect "/"
else
erb :todo_description
end
end
delete "/todos/:id" do
show_params(params)
todo_id = params[:id]
@todo = Todo.get(todo_id)
@todo.destroy
redirect "/"
end