forked from sNKS/rhodes-api-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topic.rb
79 lines (64 loc) · 1.69 KB
/
topic.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
require 'rdiscount'
class Topic
def text_only
@body = @body.gsub(/\<[^\<]+\>/,'')
self
end
def self.load(topic, source)
topic = new(topic, source)
topic.parse
return topic
end
def self.all_topics
dirs = AppConfig['dirs'] || {}
paths = dirs.values.map! { |path| path += "*.txt" }
FileList[paths]
end
attr_reader :topic, :title, :content, :toc, :intro, :body
def initialize(name, source)
@topic = name
@source = source
end
def parse
@topic = topic
@content = markdown(source)
@title, @content = _title(@content)
@toc, @content = _toc(@content)
if @toc.any?
@intro, @body = @content.split('<h2>', 2)
@body = "<h2>#{@body}"
else
@intro, @body = '', @content
end
end
protected
def source
@source
end
def notes(source)
source.gsub(
/NOTE: (.*?)\n\n/m,
"<table class='note'>\n<td class='icon'></td><td class='content'>\\1</td>\n</table>\n\n"
)
end
def markdown(source)
html = RDiscount.new(notes(source), :smart).to_html
# parse custom {lang} definitions to support syntax highlighting
html.gsub(/<pre><code>\{(\w+)\}/, '<pre><code class="brush: \1;">')
end
def _title(content)
title = content.match(/<h1>(.*)<\/h1>/)[1]
content_minus_title = content.gsub(/<h1>.*<\/h1>/, '')
return title, content_minus_title
end
def slugify(title)
title.downcase.gsub(/[^a-z0-9 -]/, '').gsub(/ /, '-')
end
def _toc(content)
toc = content.scan(/<h2>([^<]+)<\/h2>/m).to_a.map { |m| m.first }
content_with_anchors = content.gsub(/(<h2>[^<]+<\/h2>)/m) do |m|
"<a name=\"#{slugify(m.gsub(/<[^>]+>/, ''))}\"></a>#{m}"
end
return toc, content_with_anchors
end
end