2010-04-06 18:20:27 -04:00
|
|
|
require 'active_support/core_ext/object/blank'
|
2010-05-29 15:36:13 -04:00
|
|
|
require 'active_support/core_ext/string/inflections'
|
2010-04-06 18:20:27 -04:00
|
|
|
|
2009-02-05 20:57:02 -05:00
|
|
|
module RailsGuides
|
|
|
|
class Indexer
|
2010-04-06 18:20:27 -04:00
|
|
|
attr_reader :body, :result, :warnings, :level_hash
|
2009-02-05 20:57:02 -05:00
|
|
|
|
2010-04-06 18:20:27 -04:00
|
|
|
def initialize(body, warnings)
|
|
|
|
@body = body
|
|
|
|
@result = @body.dup
|
|
|
|
@warnings = warnings
|
2009-02-05 20:57:02 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def index
|
|
|
|
@level_hash = process(body)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2010-04-06 18:20:27 -04:00
|
|
|
def process(string, current_level=3, counters=[1])
|
2009-02-05 20:57:02 -05:00
|
|
|
s = StringScanner.new(string)
|
|
|
|
|
2012-02-09 05:47:34 -05:00
|
|
|
level_hash = {}
|
2009-02-05 20:57:02 -05:00
|
|
|
|
|
|
|
while !s.eos?
|
2010-04-06 18:20:27 -04:00
|
|
|
re = %r{^h(\d)(?:\((#.*?)\))?\s*\.\s*(.*)$}
|
|
|
|
s.match?(re)
|
2009-02-05 20:57:02 -05:00
|
|
|
if matched = s.matched
|
2010-04-06 18:20:27 -04:00
|
|
|
matched =~ re
|
|
|
|
level, idx, title = $1.to_i, $2, $3.strip
|
2009-02-05 20:57:02 -05:00
|
|
|
|
|
|
|
if level < current_level
|
|
|
|
# This is needed. Go figure.
|
|
|
|
return level_hash
|
|
|
|
elsif level == current_level
|
|
|
|
index = counters.join(".")
|
2010-04-06 18:20:27 -04:00
|
|
|
idx ||= '#' + title_to_idx(title)
|
2009-02-05 20:57:02 -05:00
|
|
|
|
2010-04-06 18:20:27 -04:00
|
|
|
raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{idx}). #{index} #{title}")
|
2009-02-05 20:57:02 -05:00
|
|
|
|
2009-02-24 07:29:25 -05:00
|
|
|
key = {
|
|
|
|
:title => title,
|
2010-04-06 18:20:27 -04:00
|
|
|
:id => idx
|
2009-02-24 07:29:25 -05:00
|
|
|
}
|
2009-02-05 20:57:02 -05:00
|
|
|
# Recurse
|
|
|
|
counters << 1
|
2009-02-24 07:29:25 -05:00
|
|
|
level_hash[key] = process(s.post_match, current_level + 1, counters)
|
2009-02-05 20:57:02 -05:00
|
|
|
counters.pop
|
|
|
|
|
|
|
|
# Increment the current level
|
|
|
|
last = counters.pop
|
|
|
|
counters << last + 1
|
|
|
|
end
|
|
|
|
end
|
|
|
|
s.getch
|
|
|
|
end
|
|
|
|
level_hash
|
|
|
|
end
|
2010-04-06 18:20:27 -04:00
|
|
|
|
|
|
|
def title_to_idx(title)
|
2010-05-29 15:36:13 -04:00
|
|
|
idx = title.strip.parameterize.sub(/^\d+/, '')
|
2010-04-06 18:20:27 -04:00
|
|
|
if warnings && idx.blank?
|
|
|
|
puts "BLANK ID: please put an explicit ID for section #{title}, as in h5(#my-id)"
|
|
|
|
end
|
|
|
|
idx
|
|
|
|
end
|
2009-02-05 20:57:02 -05:00
|
|
|
end
|
|
|
|
end
|