class RailsGuides::Indexer - rails-4.2.3 Documentation

# class RailsGuides::Indexer

### Attributes

body[R]
level_hash[R]
result[R]
warnings[R]

### Public Class Methods

new(body, warnings) click to toggle source

    # File guides/rails_guides/indexer.rb, line 8
    def initialize(body, warnings)
      @body     = body
      @result   = @body.dup
      @warnings = warnings
    end

### Public Instance Methods

index() click to toggle source

    # File guides/rails_guides/indexer.rb, line 14
    def index
      @level_hash = process(body)
    end

### Private Instance Methods

process(string, current_level=3, counters=[1]) click to toggle source

    # File guides/rails_guides/indexer.rb, line 20
    def process(string, current_level=3, counters=[1])
      s = StringScanner.new(string)

      level_hash = {}

      while !s.eos?
        re = %r{^h(\d)(?:\((#.*?)\))?\s*\.\s*(.*)$}
        s.match?(re)
        if matched = s.matched
          matched =~ re
          level, idx, title = $1.to_i, $2, $3.strip

          if level < current_level
            # This is needed. Go figure.
            return level_hash
          elsif level == current_level
            index = counters.join(".")
            idx ||= '#' + title_to_idx(title)

            raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{idx}). #{index} #{title}")

            key = {
              :title => title,
              :id => idx
            }
            # Recurse
            counters << 1
            level_hash[key] = 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

title_to_idx(title) click to toggle source

    # File guides/rails_guides/indexer.rb, line 60
    def title_to_idx(title)
      idx = title.strip.parameterize.sub(/^\d+/, '')
      if warnings && idx.blank?
        puts "BLANK ID: please put an explicit ID for section #{title}, as in h5(#my-id)"
      end
      idx
    end