forked from RubyChinaTranslation/Rails-Guides-China
-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathbody_converter.rb
executable file
·83 lines (67 loc) · 2.21 KB
/
body_converter.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
#coding: utf-8
require "rails_guides/indexer"
require "rails_guides/markdown_render"
module RailsGuides
class BodyConverter
attr_accessor :body, :markup, :view, :header_capture,:lb
def initialize(body,view,markup)
@markup = markup
@body = body
@view = view
if @markup == "textile"
@header_capture = /h2\.(.*)/
@lb = lambda { |text,lite_mode| textile(text,lite_mode) }
else
@header_capture = /##\s*(.*)/
@lb = lambda { |text,void| markdown(text) }
end
end
def convert_body
set_header_section
body = set_index
lb.call(body,false).html_safe
end
def set_header_section
body.sub!(/(.*?)endprologue\./m, '').strip!
header = $1
header =~ header_capture
page_title = "Ruby on Rails Guides 中文: #{$1.strip}"
header = lb.call(header,false)
view.content_for(:page_title) { page_title.html_safe }
view.content_for(:header_section) { header.html_safe }
end
def set_index
index = <<-INDEX
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />目录</h3>
<ol class="chapters">
INDEX
i = Indexer.new(body,@markup)
i.index
i.level_hash.each do |key, value|
link = view.content_tag(:a, :href => key[:id]) { lb.call(key[:title],true).html_safe }
children = value.keys.map do |k|
view.content_tag(:li,
view.content_tag(:a, :href => k[:id]) { lb.call(k[:title],true).html_safe })
end
children_ul = children.empty? ? "" : view.content_tag(:ul, children.join(" ").html_safe)
index << view.content_tag(:li, link.html_safe + children_ul.html_safe)
end
index << '</ol>'
index << '</div>'
view.content_for(:index_section) { index.html_safe }
i.result
end
def textile(body, lite_mode)
t = RedCloth.new(body)
t.hard_breaks = false
t.lite_mode = lite_mode
t.to_html(:notestuff, :plusplus_textile, :code)
end
def markdown(body)
rndr = MarkdownRender.new :with_toc_data => true
md = Redcarpet::Markdown.new rndr, :table => true
md.render body
end
end
end