Ruby on Rails to_xml nil="True"

1.2k views Asked by At

I need your help on to_xml function. How can i make all nil="True" value to a default value '' (blank) when exporting to xml from active record.

2

There are 2 answers

0
Carl Zulauf On

The #to_xml method Rails adds to ActiveRecord, Array, and Hash uses the builder gem by default. The XML is also passed through ActiveSupport::XmlMini where the addition of the nil="true" attribute is hard coded to always be added for nil attributes.

You should probably look at using builder directly to build your XML if these values are problematic.

Builder::XmlMarkup.new.object{|xml| xml.value "" }
#=> "<object><value></value></object>"

You could also use other XML libraries. I only recommend builder because it is the rails default and likely already installed.

Another option is to convert the object into a Hash first (object.attributes works if object is an ActiveRecord instance). You can then convert any nils into blank strings.

data = object.attributes
data.each_pair{|col, val| data[col] = "" if val.nil? }
data.to_xml
0
Patrick Oscity On

You can add a method to set special default values for XML generation. This method can then be called from an overridden to_xml method which duplicates the record in memory, sets default values and finally generates the xml. Example code:

class Post < ActiveRecord::Base
  def set_xml_defaults
    blanks = self.attributes.find_all{|k,v| v.nil? }.map{|k,v| [k,''] }
    self.attributes = Hash[blanks]
  end

  alias_method :to_xml_no_defaults, :to_xml

  def to_xml(options = {}, &block)
    dup = self.dup
    dup.set_xml_defaults
    dup.to_xml_no_defaults
  end
end