Sha256: 44897e145c8a2b59685001854a828a4313921df570a967fa587ec40ccdf431b0

Contents?: true

Size: 978 Bytes

Versions: 3

Compression:

Stored size: 978 Bytes

Contents

# encoding: utf-8
module Kitabu
  class Toc
    include REXML::StreamListener

    def initialize
      @toc = ""
      @previous_level = 0
      @tag = nil
      @stack = []
    end

    def header?(tag=nil)
      tag ||= @tag_name
      return false unless tag.to_s =~ /h[2-6]/
      @tag_name = tag
      return true
    end

    def in_header?
      @in_header
    end

    def tag_start(name, attrs)
      @tag_name = name
      return unless header?(name)
      @in_header = true
      @current_level = name.gsub!(/[^2-6]/, '').to_i
      @stack << @current_level
      @id = attrs["id"]
    end

    def tag_end(name)
      return unless header?(name)
      @in_header = false
      @previous_level = @current_level
    end

    def text(str)
      return unless in_header?
      @toc << %(<div class="level#{@current_level} #{@id}"><a href="##{@id}"><span>#{str}</span></a></div>)
    end

    def method_missing(*args)
    end

    def to_s
      @toc
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
kitabu-0.4.7 lib/kitabu/toc.rb
kitabu-0.4.6 lib/kitabu/toc.rb
kitabu-0.4.5 lib/kitabu/toc.rb