module Xeroizer::Record::XmlHelper::InstanceMethods

Public Instance Methods

to_xml(b = Builder::XmlMarkup.new(:indent => 2)) click to toggle source

Turn a record into its XML representation.

# File lib/xeroizer/record/xml_helper.rb, line 62
def to_xml(b = Builder::XmlMarkup.new(:indent => 2))
  optional_root_tag(parent.class.optional_xml_root_name, b) do |c|
    c.tag!(model.class.xml_node_name || model.model_name) {
      attributes.each do | key, value |
        field = self.class.fields[key]
        value = self.send(key) if field[:calculated]
        xml_value_from_field(b, field, value) unless value.nil?
      end
    }
  end
end

Protected Instance Methods

association_to_xml(association_name) click to toggle source
# File lib/xeroizer/record/xml_helper.rb, line 132
def association_to_xml(association_name)
  builder = Builder::XmlMarkup.new(indent: 2)
  records = send(association_name)

  optional_root_tag(association_name.to_s.camelize, builder) do |b|
    records.each { |record| record.to_xml(b) }
  end
end
optional_root_tag(root_name, b) { |c| ... } click to toggle source

Add top-level root name if required. E.g. Payments need specifying in the form:

<Payments>
  <Payment>
    ...
  </Payment>
</Payments>
# File lib/xeroizer/record/xml_helper.rb, line 83
def optional_root_tag(root_name, b, &block)
  if root_name
    b.tag!(root_name) { |c| yield(c) }
  else
    yield(b)
  end
end
xml_value_from_field(b, field, value) click to toggle source

Format an attribute for use in the XML passed to Xero.

# File lib/xeroizer/record/xml_helper.rb, line 92
def xml_value_from_field(b, field, value)
  case field[:type]
    when :guid        then b.tag!(field[:api_name], value)
    when :string      then b.tag!(field[:api_name], value)
    when :boolean     then b.tag!(field[:api_name], value ? 'true' : 'false')
    when :integer     then b.tag!(field[:api_name], value.to_i)
    when :decimal   
      real_value = case value
        when BigDecimal   then value.to_s
        when String       then BigDecimal(value).to_s
        else              value
      end
      b.tag!(field[:api_name], real_value)

    when :date
      real_value = case value
        when Date         then value.strftime("%Y-%m-%d")
        when Time         then value.utc.strftime("%Y-%m-%d")
        when NilClass     then nil
        else raise ArgumentError.new("Expected Date or Time object for the #{field[:api_name]} field")
      end
      b.tag!(field[:api_name], real_value)
      
    when :datetime    then b.tag!(field[:api_name], value.utc.strftime("%Y-%m-%dT%H:%M:%S"))
    when :belongs_to  
      value.to_xml(b)
      nil

    when :has_many    
      if value.size > 0
        sub_parent = value.first.parent
        b.tag!(sub_parent.class.xml_root_name || sub_parent.model_name.pluralize) {
          value.each { | record | record.to_xml(b) }
        }
        nil
      end

  end
end