-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.rb
More file actions
96 lines (80 loc) · 1.8 KB
/
app.rb
File metadata and controls
96 lines (80 loc) · 1.8 KB
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
96
# frozen_string_literal: true
require 'sinatra'
require 'pg'
require './lib/crud_controller'
my_db = CrudController.new('sinatra_db', 'sinatra_table')
get '/' do
notes = my_db.read_all_note
a_tags = to_link(notes)
@notes_in_ul_tag = to_ul(a_tags)
erb :index
end
get '/composition' do
erb :compose
end
post '/note' do
my_db.create_note(params[:title], params[:body])
@notes = my_db.read_all_note
redirect to('/')
end
get '/note/:id' do
if my_db.id_exist?(params[:id])
@note = my_db.read_note(params[:id])
erb :show
else
erb :not_found
end
end
get '/editing/note/:id' do
if my_db.id_exist?(params[:id])
@note = my_db.read_note(params[:id])
erb :edit
else
erb :not_found
end
end
patch '/note/:id' do
if my_db.id_exist?(params[:id])
my_db.update_note(params[:id], params[:title], params[:body])
@notes = my_db.read_all_note
redirect to('/')
else
erb :not_found
end
end
delete '/note/:id' do
if my_db.id_exist?(params[:id])
my_db.delete_note(params[:id])
@notes = my_db.read_all_note
redirect to('/')
else
erb :not_found
end
end
not_found do
erb :not_found
end
helpers do
def to_link(notes)
notes.map do |note|
title = justify_title(note['title'], 40)
"<a href='/note/#{note['id']}'>#{escape_html(title)}</a>"
end
end
def to_ul(a_tags)
li_tags = a_tags.map do |atag|
"<li>#{atag}</li>"
end.join
"<ul>#{li_tags}</ul>"
end
def justify_title(title_string, max_byte_size)
return_string = +''
title_string.chars.each do |string|
return_string.bytesize < max_byte_size ? return_string << string : break
end
return_string.bytesize <= title_string.bytesize - 3 ? "#{return_string}..." : return_string
end
def escape_html(text)
Rack::Utils.escape_html(text)
end
end