Class: DoctorNinja::Parsers::List

Inherits:
Base
  • Object
show all
Defined in:
lib/doctor_ninja/parsers/list.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#initialize, #parse_children

Constructor Details

This class inherits a constructor from DoctorNinja::Parsers::Base

Class Method Details

.applicable_to?(node) ⇒ Boolean

Returns:

  • (Boolean)


4
5
6
# File 'lib/doctor_ninja/parsers/list.rb', line 4

def self.applicable_to?(node)
  node.name == "p" && node.xpath("./w:pPr/w:numPr").length > 0
end

Instance Method Details

#get_pr(pr, node) ⇒ Object



62
63
64
65
66
# File 'lib/doctor_ninja/parsers/list.rb', line 62

def get_pr pr, node
  node.xpath(".//#{pr}/@w:val")[0].value
rescue
  nil
end

#parseObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/doctor_ninja/parsers/list.rb', line 8

def parse
  num_id = get_pr "w:numId", @node
  lvl = get_pr "w:ilvl", @node
  style = @document.numbering.style(lvl, num_id)
  tag = style == "bullet" ? "ul" : "ol"
  type = case style
  when "lowerRoman"
    "i"
  when "upperRoman"
    "I"
  when "lowerLetter"
    "a"
  when "upperLetter"
    "A"
  else
    ""
  end
  typeAttr = type == "" ? "" : " type='#{type}'"

  num_id_query = ".//w:numId/@w:val=\"#{num_id}\""

  previous = @node.xpath("preceding-sibling::w:p[#{num_id_query}][1]")
  following = @node.xpath("following-sibling::w:p[#{num_id_query}][1]")

  prefix = ""
  # Add <ul> if is start of new list
  if previous.length == 0 || get_pr("w:ilvl", previous).to_i < lvl.to_i
    prefix += "<#{tag}#{typeAttr}>"
  end

  prefix += "<li>"
  
  suffix = ""

  f_lvl = (following.length == 0) ? -1 : get_pr("w:ilvl", following)

  closings = (f_lvl.to_i..lvl.to_i).map do |l|
    if l == lvl.to_i
      # Close only this item
      "</li>"
    elsif l < lvl.to_i && l >= 0
      # Close list level
      "</#{tag}></li>"
    else
      # Close entire list
      "</#{tag}>"
    end
  end.reverse

  suffix = closings.join("")

  "#{prefix}#{parse_children}#{suffix}"
end