Overriding to_xml in Rails 2.1

Tagged with Rails ActiveRecord Ruby

Language: Ruby

View as text

class Project < ActiveRecord::Base  

  # This method replaces the original to_xml method
  # via alias_method_chain. 
  # We swap out the old version with this new one
  # that calls the old version and builds on it.
  def to_xml_with_new_xml_data(options = {:indent => 2})
    # If you don't do this next  line, Array#to_xml won't work!!!
    xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])

    
    # now do the real work - notice the method name we call here.
    # Also notice how we pass the builder object to the to_xml method.
    # This preserves the indentation.
    self.to_xml_without_new_xml_data(builder => xml, :include => [:tasks, :notes],
                                            :methods => [:total_hours. :another_method],
                                            :except=>[:user_id]
                                           ) 
  end
  
  
  alias_method_chain :to_xml, :new_xml_data
  
end
Original snippet written by Brian Hogan
Last updated at 00:17 AM on Jul 07, 2008 by Brian Hogan

SnippetStash costs money to host and develop. The service is free for everyone to use
but if you found it useful please consider making a small donation.