module Xeroizer::Record::XmlHelper::ClassMethods

Public Instance Methods

build_from_node(node, parent, base_module) click to toggle source

Build a record instance from the XML node.

# File lib/xeroizer/record/xml_helper.rb, line 15
def build_from_node(node, parent, base_module)
  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(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
        when :belongs_to  
          model_name = field[:model_name] ? field[:model_name].to_sym : element.name.to_sym
          base_module.const_get(model_name).build_from_node(element, parent, base_module)
          
        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, inner_element |
              list << base_module.const_get(sub_field_name).build_from_node(inner_element, sub_parent, base_module)
            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