Customizing XML generation in Rails
I am new to Rails and I have written a few models. One of the XML generated by a model looks like this:
<book>
<read type="boolean">true</read>
<title>Julius Caesar</title>
<id type="integer">1</id>
</book>
The serialized XML is good but I want to have more control over it. I want to generate the same in a different format. Like:
<book read="true" id="1">
<title>Julius Caesar</t开发者_运维百科itle>
</book>
How do I achieve this? I have done some research and found that the to_xml method should be overridden. But am not sure how to do it.
You can use a custom ::Builder::XmlMarkup
for this. However, the documentation about Active Record Serialization (see last code example) is buggy. You can do it like this:
class Book < ActiveRecord::Base
def to_xml(options = {})
# Load builder of not loaded yet
require 'builder' unless defined? ::Builder
# Set indent to two spaces
options[:indent] ||= 2
# Initialize Builder
xml = options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
# This is were the real action starts
xml.book :read => read, :id => id do
xml.title self.title
end
end
end
精彩评论