-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.rb
95 lines (81 loc) · 1.94 KB
/
app.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
94
95
require "roda"
require_relative "./models"
class App < Roda
plugin :all_verbs
plugin :public
plugin :json
plugin :halt
plugin :json_parser
plugin :render, engine: "slim"
plugin :symbol_views
plugin :indifferent_params
route do |r|
r.public
r.root do
{ status: "ok" }
end
# path: /posts
r.on "posts" do
r.is do
# GET
r.get do
{
posts: Post.all.map(&:values)
}
end
# POST
r.post do
r.halt(403, { errors: ["'post' params is missing"] }) unless params[:post]
post = Post.new
post.set_fields(params[:post], ["title", "body"])
if post.save
{ post: post.values }
else
{
post: post.values,
errors: post.errors,
}
end
end
end
# path: /posts/:id
r.on Integer do |id|
@post = Post[id]
r.is do
# GET
r.get do
@post.to_hash.merge({
comments_path: "/posts/#{@post.id}/comments"
})
end
end
# path: /posts/:id/comments
r.on "comments" do
r.is do
# GET
r.get do
{
comments: @post.comments.map(&:values)
}
end
# POST
r.post do
r.halt(403, { errors: ["'comment' params is missing"] }) unless params[:comment]
comment = Comment.new(post: @post)
comment.set_fields(params[:comment], ["name", "body"])
if comment.save
{ comment: comment.values }
else
{
comment: comment.values,
errors: comment.errors
}
end
end
end
end # /comments
end
end
end
Dir['./helpers/*.rb'].each{|f| require f}
end