Class: ReVIEW::EPUBMaker::ReVIEWHeaderListener

Inherits:
Object
  • Object
show all
Includes:
REXML::StreamListener
Defined in:
lib/review/epubmaker/reviewheaderlistener.rb

Overview

Listener class to scan HTML and get heading information

The heading information this listener will retrieve is as follows:

  • level: Heading level (1..6)

  • id: HTMl ID attribute. Basically the ‘id` attribute of the h(1-6) element, but if there is an `a` element within the h(1-6) element, it will be its `id` attribute.

  • title: The title string of the headline. Usually, it is the text within the h(1-6) element, but if there is an ‘img` element, it will be the text with its `alt` attribute.

  • notoc: The ‘notoc` attribute of the headline element.

Instance Method Summary collapse

Constructor Details

#initialize(headlines) ⇒ ReVIEWHeaderListener

Returns a new instance of ReVIEWHeaderListener.



21
22
23
24
25
# File 'lib/review/epubmaker/reviewheaderlistener.rb', line 21

def initialize(headlines)
  @level = nil
  @content = ''
  @headlines = headlines
end

Instance Method Details

#tag_end(name) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/review/epubmaker/reviewheaderlistener.rb', line 43

def tag_end(name)
  if name =~ /\Ah\d+/
    if @id.present?
      @headlines.push({ 'level' => @level,
                        'id' => @id,
                        'title' => @content,
                        'notoc' => @notoc })
    end
    @content = ''
    @level = nil
    @id = nil
    @notoc = nil
  end

  true
end

#tag_start(name, attrs) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/review/epubmaker/reviewheaderlistener.rb', line 27

def tag_start(name, attrs)
  if name =~ /\Ah(\d+)/
    raise "#{name}, #{attrs}" if @level.present?

    @level = $1.to_i
    @id = attrs['id'] if attrs['id'].present?
    @notoc = attrs['notoc'] if attrs['notoc'].present?
  elsif @level.present? # if in <hN> tag
    if name == 'img' && attrs['alt'].present?
      @content << attrs['alt']
    elsif name == 'a' && attrs['id'].present?
      @id = attrs['id']
    end
  end
end

#text(text) ⇒ Object



60
61
62
63
64
# File 'lib/review/epubmaker/reviewheaderlistener.rb', line 60

def text(text)
  if @level.present?
    @content << text.tr("\t", ' ')
  end
end