当#method_name返回一个数组时,Rails 2:#to_xml(:methods =>:method_name)

时间:2013-03-21 00:59:47

标签: ruby-on-rails xml-serialization ruby-on-rails-2 ruby-1.8.7

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

鉴于#numbers不是字段而是方法 和@ 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>"

(格式化,因此很容易阅读)

提前感谢您的建议!

2 个答案:

答案 0 :(得分: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>
    

答案 1 :(得分: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