-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBook Viewer App- Sinatra Framework, Backend
71 lines (54 loc) · 1.36 KB
/
Book Viewer App- Sinatra Framework, Backend
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
require "sinatra"
require "sinatra/reloader" if development?
require "tilt/erubis"
before do
@contents = File.readlines("data/toc.txt")
end
not_found do
redirect "/"
end
def each_chapter
@contents.each_with_index do |name, index|
number = index + 1
contents = File.read("data/chp#{number}.txt")
yield number, name, contents
end
end
def chapters_matching(query)
results = []
return results unless query
each_chapter do |number, name, contents|
matches = {}
contents.spit("\n\n").each_with_index do |paragraph, index|
matches[index] = paragraph if paragraph.include?(query)
end
results << {number: number, name: name, paragraphs: matches} if matches.any?
end
results
end
get "/search" do
@results = chapters_matching(params[:query])
erb :search
end
helpers do
def in_paragraphs(text)
text.split("\n\n").map do |paragraph|
"<p id=paragraph#{index}>#{line}</p>"
end.join
end
def highlight(text, term)
text.gsub(term, %(<strong>#{term}</strong>))
end
end
get "/" do
@title = "The Adventures of Sherlock Holmes"
erb :home
end
get "/chapters/:number" do
number = params[:number].to_i
chapter_name = @contents[number - 1]
redirect "/" unless ([email protected]).cover? number
@title = "Chapter #{number}: #{chapter_name}"
@chapter = File.read("data/chp#{number}.txt")
erb :chapter
end