开发者

Customizing XML generation in Rails

开发者 https://www.devze.com 2023-04-12 15:55 出处:网络
I am new to Rails and I have written a few models. One of the XML generated by a model looks like this:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号