-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemo.rb
90 lines (67 loc) · 1.71 KB
/
memo.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
# frozen_string_literal: true
require 'sinatra'
require 'sinatra/reloader'
require 'pg'
helpers do
def h(text)
Rack::Utils.escape_html(text)
end
end
class Memo
def initialize
@connect = PG.connect(host: 'localhost', dbname: 'mydb', port: '5432')
end
def list
@connect.exec('select * from books order by id asc').to_a
end
def insert(new_memo_id, title, content)
@connect.exec('INSERT INTO books VALUES ($1, $2, $3)', [new_memo_id, title, content])
end
def update(title, content, id)
@connect.exec('update books set title=$1, body=$2 where id=$3', [title, content, id])
end
def delete(id)
@connect.exec('delete from books where id=$1', [id])
end
end
memo = Memo.new
get '/' do
redirect to('/memos')
end
get '/memos' do
@memos = memo.list
erb :index
end
get '/memos/new' do
erb :new
end
post '/memos' do
@memos = memo.list
# 新規メモの、ID番号を決める処理。
if @memos.empty?
new_memo_id = 1
else
id_aggregation = @memos.map { |data| data['id'].to_i }
new_memo_id = (id_aggregation.max + 1) # 「既存メモの最大ID + 1」 に新規メモのIDを設定する。
end
memo.insert(new_memo_id, params['title'], params['content'])
redirect "/memos/#{new_memo_id}"
end
get '/memos/:id' do
@memo = memo.list.find { |data| data['id'].to_i == params['id'].to_i }
erb :detail
end
get '/memos/:id/edit' do
@memo = memo.list.find { |data| data['id'].to_i == params['id'].to_i }
erb :edit
end
patch '/memos/:id' do
memo.update(params['title'], params['content'], params['id'])
@memos = memo.list
redirect "/memos/#{params['id']}"
end
delete '/memos/:id' do
memo.delete(params['id'])
@memos = memo.list
redirect '/'
end