Module: AcDc::Parsing

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

Instance Method Summary collapse

Instance Method Details

#acdc(xml, options = {}) ⇒ 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
44
45
46
47
# File 'lib/acdc/parse.rb', line 4

def acdc(xml, options={})
  
  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 = constantize(node.name)
  
  root = node.name.downcase == klass.tag_name
  
  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 options[:single] || root
    collection.first
  else
    collection
  end
end