-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.rb
94 lines (74 loc) · 1.9 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
require 'rubygems'
require 'sinatra'
require 'data_mapper'
require 'json'
##################
# Database setup #
##################
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/app.db")
##########
# Models #
##########
class Category
include DataMapper::Resource
property :id, Serial
property :name, String
has n, :templates
end
class Template
include DataMapper::Resource
property :id, Serial
property :name, String
property :body, String
belongs_to :category
end
DataMapper.finalize
Category.auto_upgrade!
Template.auto_upgrade!
##########
# Routes #
##########
# Root route (lol)
get '/' do
File.read(File.join('public', 'index.html'))
end
# Categories#index
get '/categories/?' do
Category.all.to_json
end
# Categories#show
get '/categories/:id/?' do
Category.get(params[:id]).to_json
end
# Categories#create
post '/categories/?' do
Category.create(JSON.parse(request.body.read)).to_json
end
# Categories#update
put '/categories/:id/?' do
Category.get(params[:id]).tap { |c| c.update(JSON.parse(request.body.read)) }.to_json
end
# Categories#destroy
delete '/categories/:id/?' do
Category.get(params[:id]).destroy
end
# Templates#index
get '/categories/:category_id/templates/?' do
Category.get(params[:category_id]).templates.to_json
end
# Templates#show
get '/categories/:category_id/templates/:id/?' do
Category.get(params[:category_id]).templates.get(params[:id]).to_json
end
# Templates#create
post '/categories/:category_id/templates/?' do
Category.get(params[:category_id]).templates.create(JSON.parse(request.body.read)).to_json
end
# Templates#update
put '/categories/:category_id/templates/:id/?' do
Category.get(params[:category_id]).templates.get(params[:id]).tap { |t| t.update(JSON.parse(request.body.read)) }.to_json
end
# Templates#destroy
delete '/categories/:category_id/templates/:id/?' do
Category.get(params[:category_id]).templates.get(params[:id]).destroy
end