blob: 52809829e2028ac2a2f75988f95342e016057d22 (
plain) (
blame)
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
|
module RailsGuides
class Indexer
attr_reader :body, :result, :level_hash
def initialize(body)
@body = body
@result = @body.dup
end
def index
@level_hash = process(body)
end
private
def process(string, current_level= 3, counters = [1])
s = StringScanner.new(string)
level_hash = ActiveSupport::OrderedHash.new
while !s.eos?
s.match?(/\h[0-9]\..*$/)
if matched = s.matched
matched =~ /\h([0-9])\.(.*)$/
level, title = $1.to_i, $2
if level < current_level
# This is needed. Go figure.
return level_hash
elsif level == current_level
index = counters.join(".")
bookmark = '#' + title.gsub(/[^a-z0-9\-_\+]+/i, '').underscore.dasherize
raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{bookmark}). #{index}#{title}")
# Recurse
counters << 1
level_hash[title.strip] = process(s.post_match, current_level + 1, counters)
counters.pop
# Increment the current level
last = counters.pop
counters << last + 1
end
end
s.getch
end
level_hash
end
end
end
|