forked from sinatra/sinatra-book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
book.rb
67 lines (61 loc) · 1.53 KB
/
book.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
require 'pdfkit'
require 'redcarpet'
require 'fileutils'
module Book
ASSETS_DIR = File.join(File.dirname(__FILE__), "assets")
BOOK_DIR = File.join(File.dirname(__FILE__), "book")
OUTPUT_DIR = File.join(File.dirname(__FILE__), "output")
def build(pdf=false)
doc = header
doc << toc
doc << content
if pdf
kit = PDFKit.new(doc, :page_size=>'Letter')
kit.stylesheets << "#{ASSETS_DIR}/print.css"
pdf = kit.to_pdf
FileUtils.mkdir_p OUTPUT_DIR
file = kit.to_file("#{OUTPUT_DIR}/sinatra-book.pdf")
end
return doc
end
private
def header
<<-header
<div id="header">
<p>
<img src="#{ASSETS_DIR}/images/book-logo.png" />
</p>
</div>
header
end
def toc
toc_renderer = Redcarpet::Markdown.new(Redcarpet::Render::HTML_TOC)
<<-toc
<div id="toc">
#{toc_renderer.render(complete_markdown)}
</div>
toc
end
def content
renderer = Redcarpet::Markdown.new(
Redcarpet::Render::HTML.new(:with_toc_data => true),
:fenced_code_blocks => true)
<<-content
<div id="content">
#{renderer.render(complete_markdown)}
</div>
content
end
def complete_markdown
s = []
File.new("book-order.txt").each_line do |line|
line.strip!
next if line =~ /^#/ # Skip comments
next if line =~ /^$/ # Skip blank lines
File.open(File.join(BOOK_DIR, line)) do |f|
s << f.read
end
end
return s.join("\n\n* * *\n\n")
end
end