Module: Median::XmlSupport

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#initialize(xml) ⇒ Object



3
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
48
# File 'lib/median/xml_support.rb', line 3

def initialize(xml)
  fields = self.class.fields

  fields.each do |name, options|
    xpath           = options[:xpath]
    wants_attribute = options[:attribute] || false
    multiple        = options[:multiple]  || false
    autosplit       = options[:autosplit] || false
    process         = options[:process]   || false
    default         = options[:default]   || false

    raise "xpath option is missing" unless xpath
    raise "boolean required for option 'multiple'" unless !!multiple == multiple

    set_field_value(name, default) if default.present?
    set_field_value(name, []) if multiple

    nodes = xml.xpath(options[:xpath])
    nodes.each do |node|
      if wants_attribute
        value = setup_value_for_field(node.attribute(wants_attribute).try(:value), process, default, autosplit)
        set_field_value(name, value)
        break;
      else
        if multiple
          values = get_field_value(name) || []

          value = setup_value_for_field(node.content, process, default, autosplit)
          if value
            if value.is_a?(Array)
              values = values + value
            else
              values << value
            end
          end

          set_field_value(name, values)
        else
          value = setup_value_for_field(node.content, process, default, autosplit)
          set_field_value(name, value)
          break;
        end
      end
    end if nodes.present?
  end if fields.present?
end