Module: Xeroizer::Record::XmlHelper::ClassMethods

Defined in:
lib/xeroizer/record/xml_helper.rb

Instance Method Summary collapse

Instance Method Details

#build_from_node(node, parent) ⇒ Object

Build a record instance from the XML node.



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
49
50
51
52
53
# File 'lib/xeroizer/record/xml_helper.rb', line 15

def build_from_node(node, parent)
  record = new(parent)
  node.elements.each do | element |
    field = self.fields[element.name.to_s.underscore.to_sym]
    if field
      value = case field[:type]
        when :guid        then element.text
        when :string      then element.text
        when :boolean     then (element.text == 'true')
        when :integer     then element.text.to_i
        when :decimal     then BigDecimal.new(element.text)
        when :date        then Date.parse(element.text)
        when :datetime    then Time.parse(element.text)
        when :datetime_utc then ActiveSupport::TimeZone['UTC'].parse(element.text).utc.round(3)
        when :belongs_to  
          model_name = field[:model_name] ? field[:model_name].to_sym : element.name.to_sym
          Xeroizer::Record.const_get(model_name).build_from_node(element, parent)
          
        when :has_many
          if element.element_children.size > 0
            sub_field_name = field[:model_name] ? field[:model_name].to_sym : element.children.first.name.to_sym
            sub_parent = record.new_model_class(sub_field_name)
            element.children.inject([]) do | list, element |
              list << Xeroizer::Record.const_get(sub_field_name).build_from_node(element, sub_parent)
            end
          end

      end
      if field[:calculated]
        record.attributes[field[:internal_name]] = value
      else
        record.send("#{field[:internal_name]}=".to_sym, value)
      end
    end
  end

  parent.mark_clean(record)
  record
end