Class: Kitabu::Toc

Inherits:
Object
  • Object
show all
Includes:
REXML::StreamListener
Defined in:
lib/kitabu/base.rb

Instance Method Summary collapse

Constructor Details

#initializeToc

Returns a new instance of Toc.



280
281
282
283
284
285
# File 'lib/kitabu/base.rb', line 280

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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args) ⇒ Object



323
324
# File 'lib/kitabu/base.rb', line 323

def method_missing(*args)
end

Instance Method Details

#header?(tag = nil) ⇒ Boolean

Returns:

  • (Boolean)


287
288
289
290
291
292
# File 'lib/kitabu/base.rb', line 287

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

#in_header?Boolean

Returns:

  • (Boolean)


294
295
296
# File 'lib/kitabu/base.rb', line 294

def in_header?
  @in_header
end

#tag_end(name) ⇒ Object



312
313
314
315
316
# File 'lib/kitabu/base.rb', line 312

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

#tag_start(name, attrs) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/kitabu/base.rb', line 298

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"]

  @toc << %(<ul class="level#{@current_level}">) if @current_level > @previous_level
  @toc << %(</li></ul>) * (@previous_level - @current_level) if @current_level < @previous_level
  @toc << %(</li>) if @current_level <= @previous_level
  @toc << %(<li>)
end

#text(str) ⇒ Object



318
319
320
321
# File 'lib/kitabu/base.rb', line 318

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

#to_sObject



326
327
328
329
330
# File 'lib/kitabu/base.rb', line 326

def to_s
  @toc + (%(</li></ul>) * (@stack.last - 1))
rescue
  ""
end