Class: Eatr::Xml::Document

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
ParseValue
Defined in:
lib/eatr/xml/document.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ParseValue

#parse_value

Constructor Details

#initialize(schema_path) ⇒ Document

Returns a new instance of Document.



17
18
19
# File 'lib/eatr/xml/document.rb', line 17

def initialize(schema_path)
  @schema = Schema.new(YAML.load(File.read(schema_path)))
end

Instance Attribute Details

#schemaObject (readonly)

Returns the value of attribute schema.



12
13
14
# File 'lib/eatr/xml/document.rb', line 12

def schema
  @schema
end

Instance Method Details

#parse(xml_document_path) ⇒ Object



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/eatr/xml/document.rb', line 21

def parse(xml_document_path)
  @namespaces = {}

  if File.exists?(xml_document_path)
    file = File.open(xml_document_path)
  else
    file = StringIO.new(xml_document_path)
  end

  doc = Nokogiri::XML(file) do |config|
    config.strict.nonet
  end

  if @schema.remove_namespaces?
    doc.remove_namespaces!
    @namespaces = {}
  else
    @namespaces = doc.collect_namespaces
  end

  cardinality = @schema.fields.inject(1) do |memo, field|
    if field.node?
      memo * [doc.xpath(field.xpath, @namespaces).count, 1].max
    else
      memo
    end
  end

  objects = []

  cardinality.times do |n|
    objects << @schema.to_struct.new
  end

  @schema.fields.each do |field|
    objects = set_field(objects, doc, field)
  end

  objects
end