Class: XmlUtils::Formatters::Default

Inherits:
Object
  • Object
show all
Defined in:
lib/xmlutils/formatters.rb

Direct Known Subclasses

Pretty

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(compact = false) ⇒ Default

Returns a new instance of Default.



23
24
25
# File 'lib/xmlutils/formatters.rb', line 23

def initialize(compact = false)
  @compact = compact
end

Instance Attribute Details

#compactObject

Returns the value of attribute compact.



21
22
23
# File 'lib/xmlutils/formatters.rb', line 21

def compact
  @compact
end

Instance Method Details

#write(node, output = $stdout) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/xmlutils/formatters.rb', line 27

def write(node, output = $stdout)
  case node
  when Document
    node.children.each_with_index do |child, idx|
      write(child, output)
      output << "\n" unless idx == node.children.length - 1
    end
  when Element
    write_element(node, output, 0)
  when Text
    output << node.to_s
  when CData
    output << node.to_s
  when Comment
    output << node.to_s
  when ProcessingInstruction
    output << node.to_s
  when XMLDecl
    output << node.to_s
  when DocType
    output << node.to_s
  end
end

#write_element(node, output, indent = 0) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/xmlutils/formatters.rb', line 51

def write_element(node, output, indent = 0)
  output << '  ' * indent
  output << "<#{node.name}"
  node.attributes.each_value do |attr|
    output << " #{attr.to_string}"
  end

  if node.children.empty?
    output << " />"
  else
    output << ">"
    has_only_text = node.children.all? { |c| c.is_a?(Text) || c.is_a?(CData) }
    if has_only_text
      node.children.each { |c| write(c, output) }
    else
      output << "\n"
      node.children.each do |c|
        write(c, output) if c.is_a?(Text) && c.to_s.strip.empty?
        next if c.is_a?(Text) && c.to_s.strip.empty?
        if c.is_a?(Element)
          write_element(c, output, indent + 1)
        else
          output << '  ' * (indent + 1)
          write(c, output)
        end
        output << "\n"
      end
      output << '  ' * indent
    end
    output << "</#{node.name}>"
  end
end