Module: AcDc::Parsing

Included in:
Object
Defined in:
lib/acdc/parse.rb

Instance Method Summary collapse

Instance Method Details

#acdc(xml) ⇒ Object



4
5
6
7
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
# File 'lib/acdc/parse.rb', line 4

def acdc(xml)
  if xml.is_a?(XML::Node)
    node = xml
  else
    if xml.is_a?(XML::Document)
      node = xml.root
    else
      node = XML::Parser.string(xml).parse.root
    end
  end
  klass = AcDc.parseable_constants.find{ |const|
    const.name.downcase =~ /#{node.name.downcase}/ || const.tag_name == node.name
  }
  if klass.nil?
    raise Exception.new("Uh Oh ... Live Wire! Couldn't parse #{node.name}.")
  end
  root = node.name.downcase == klass.tag_name.downcase
  namespace = node.namespaces.default
  namespace = "#{DEFAULT_NAMESPACE}:#{namespace}" if namespace
  xpath = root ? '/' : './/'
  xpath += "#{DEFAULT_NAMESPACE}:" if namespace
  xpath += node.name
  nodes = node.find(xpath, Array(namespace))
  collection = nodes.collect do |n|
    obj = klass.new
    klass.attributes.each do |attr|
      obj.send("#{attr.method_name}=", attr.value_from_xml(n, namespace))
    end
    klass.elements.each do |elem|
      obj.send("#{elem.method_name}=", elem.value_from_xml(n, namespace))
    end
    obj
  end
  nodes = nil
  if root
    collection.first
  else
    collection
  end
end