-
Notifications
You must be signed in to change notification settings - Fork 0
/
memo_app.rb
123 lines (102 loc) · 2.28 KB
/
memo_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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# frozen_string_literal: true
require "sinatra"
require "sinatra/reloader"
require_relative "./lib/file_list"
require_relative "./lib/json_io"
require "date"
class MemoApp < Sinatra::Base
use Rack::MethodOverride
DATAPASH = "./data"
helpers do
def h(text)
Rack::Utils.escape_html(text)
end
end
get "/" do
show_top(DATAPASH)
end
get "/create" do
erb :create, layout: :layout_edit
end
get "/:id" do |id|
show_read(id)
end
get "/:id/edit" do |id|
@id = id
set_one_memo("./data/#{@id}.json")
set_title(h(@one_memo["title"]))
@contents = h(@one_memo["contents"])
erb :edit, layout: :layout_edit
end
post "/" do
@id = new_id
set_title(params["title"])
@contents = params["contents"]
update_data("./data/#{@id}.json")
show_read(@id)
end
patch "/:id" do |id|
set_title(params["title"])
@contents = params["contents"]
update_data("./data/#{id}.json")
show_read(id)
end
delete "/:id" do |id|
File.delete("./data/#{id}.json")
show_top(DATAPASH)
end
private
def set_title(str)
@title = str
@title = "新しいメモ" if @title == ""
end
def set_one_memo(file_path)
fi = Json::Io.new(file_path)
fi.read
@one_memo = fi.data
end
def show_top(path)
files = set_files(path)
set_titles(files)
erb :top
end
def show_read(id)
@id = id
set_one_memo("./data/#{@id}.json")
@title = h(@one_memo["title"])
@contents = h(@one_memo["contents"])
erb :read
end
def set_files(path)
fl = FileList.new
fl.make(path)
fl.list
end
def set_only_file_names(path)
fl = FileList.new
fl.make(path)
check_blank(fl.only_file_names)
end
def check_blank(input)
input == [] ? ["0"] : input
end
def set_titles(files)
@titles = []
files.each do |f|
fi = Json::Io.new(f)
fi.read
@titles.push(fi.data)
end
@titles.sort_by! { |k| k["datetime"] }
end
def update_data(file_path)
in_data = { title: @title, contents: @contents, datetime: Time.now.to_i }
fi = Json::Io.new(file_path)
fi.read
fi.update(in_data)
end
def new_id
SecureRandom.uuid
end
end
MemoApp.run!