1

如果它是一个数组,是否可以覆盖#to_xml 如何呈现方法结果?

给定 #numbers 不是字段而是方法 And @object.numbers #=> [0,1,2,3,4,5]

目前它确实:

@object.to_xml(:methods => :numbers)
=> "<object><numbers>012345</numbers></object>"

是否可以覆盖此行为,使其返回:

@object.to_xml(:methods => :numbers)
=> "<object>
      <numbers>
        <number>0</number>
        <number>1</number>
        <number>2</number>
        <number>3</number>
        <number>4</number>
        <number>5</number>
      </numbers>
    </object>"

(格式化以便于阅读)

提前感谢您的建议!

4

2 回答 2

0

你有两个选择:

  1. 升级到 Rails 3。它已经有了所需的输出。

    gem "activemodel", '~> 3.2.12'
    require "active_model"
    
    # This could be an Active Record model
    class Result
      include ActiveModel::Serializers::Xml
    
      def numbers
        (0..5).to_a
      end
    
      def attributes
        {}
      end
    end
    
    result = Result.new
    puts result.to_xml(:methods => :numbers)
    

    输出:

    <?xml version="1.0" encoding="UTF-8"?>
    <result>
      <numbers type="array">
        <number type="integer">0</number>
        <number type="integer">1</number>
        <number type="integer">2</number>
        <number type="integer">3</number>
        <number type="integer">4</number>
        <number type="integer">5</number>
      </numbers>
    </result>
    
  2. 在您可以完全控制输出的情况下使用 XML Builder。您必须手动指定所有属性。

    # app/views/results/show.xml.builder
    xml.instruct!
    xml.result {
      xml.numbers {
        result.numbers.each do |n|
          xml.number n
        end
      }
    }
    

    输出:

    <?xml version="1.0" encoding="UTF-8"?>
    <result>
      <numbers>
        <number>0</number>
        <number>1</number>
        <number>2</number>
        <number>3</number>
        <number>4</number>
        <number>5</number>
      </numbers>
    </result>
    
于 2013-03-23T03:26:43.243 回答
0

您可以使用该:procs选项在模型中为您的方法添加自定义渲染:

def to_xml(options={})
  numbers_proc = Proc.new do |options|
    xml = options[:builder]
    xml.numbers do
      numbers.each do |n|
        xml.number n
      end
    end
  end
  super options.merge(:procs => numbers_proc)
end
于 2014-02-19T15:19:44.013 回答