Class: Extreml

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

Defined Under Namespace

Classes: TypeElement, XmlHeader

Instance Method Summary collapse

Constructor Details

#initialize(xml_file = nil, warnings: true, xml_header: nil) ⇒ Extreml



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
61
62
63
64
65
66
67
# File 'lib/extreml.rb', line 26

def initialize xml_file = nil, warnings: true, xml_header: nil

  # Warnings flag
  @warnings = warnings
  @header = xml_header

  if xml_file.nil?
    raise 'Error: please specify an xml file. Nil was given.'
  elsif !File.file? xml_file
    raise "Error: file #{xml_file} not found."
  else

    # Read file
    xml = File.read xml_file

    @body = Hash.new

    # Get xml header informations
    header = xml[/^\<\?xml (.*)\?\>/]

    if header.nil?
      puts "Warning: #{xml_file}: xml header missing." if @warnings
      define_singleton_method :header do
        return nil
      end
    else
      h = header.scan /([\w\?\<]*)=["|']([^'"]*)["|']/

      @xml_header = XmlHeader.new header

      define_singleton_method :header do
        return @xml_header
      end
    end

  end

  # Read document
  doc = xml.match /(?:\<\?xml .*?(?: ?\?\>))?[\t\n\r\f ]*(.*)/m
  @document = unpack doc[1]

end

Instance Method Details

#documentObject

Expose the entire document



88
89
90
# File 'lib/extreml.rb', line 88

def document
  return TypeElement.new({name: 'document', content: @document})
end

#to_hashObject

Returns the document in an Hash form



70
71
72
# File 'lib/extreml.rb', line 70

def to_hash
  return @document
end

#to_xmlObject

Retrurns the document in XML format



75
76
77
78
79
80
81
82
83
84
85
# File 'lib/extreml.rb', line 75

def to_xml
  if @xml_header.nil?
    xml = ''
  else
    xml = @xml_header.to_xml + "\n"
  end
  self.document.__types.each do |t|
    xml += self.document.send(t).to_xml
  end
  return xml
end

#tree(attributes: false) ⇒ Object

Print the entire document tree. For debug purposes



93
94
95
# File 'lib/extreml.rb', line 93

def tree attributes: false
  self.document.__tree attributes
end