Ruby to_xml更改Api请求的属性名称

时间:2015-10-06 12:11:00

标签: ruby-on-rails ruby api ruby-on-rails-4 rails-api

我想转换xml响应的密钥,以便它们与第三方Api请求匹配。

    class Person1
      include ActiveModel::Serializers::Xml

      attr_accessor :name, :age

      def attributes
        {'name' => nil, 'age' => nil}
      end

      def capitalized_name
        name.capitalize
      end
    end
p = Person1.new
p.name = "test"
puts p.to_xml

输出:: -

 <?xml version="1.0" encoding="UTF-8"?>
    <person1>
      <age nil="true"/>
      <name>test</name>
    </person1>

我正在寻找一种方法来更改xml输出中的键,如。

<?xml version="1.0" encoding="UTF-8"?>
<person1>
      <Age nil="true"/>
      <Name>test</Name>
</person1>

1 个答案:

答案 0 :(得分:1)

怎么样:

puts p.to_xml(:camelize => true)


<?xml version="1.0" encoding="UTF-8"?>
<Person1>
  <Age nil="true"/>
  <Name>test</Name>
</Person1>

或者如果大写Person困扰你,我想你可以这样做:

puts p.to_xml(:camelize => true).sub('<Person1>','<person1>').sub('</Person1>','</person1>')

<?xml version="1.0" encoding="UTF-8"?>
<person1>
  <Age nil="true"/>
  <Name>test</Name>
</person1>