Grape:如何在使用grape-entity公开集合时从XML响应中删除额外的根元素<hash>?

时间:2016-01-20 12:38:41

标签: ruby-on-rails ruby xml grape grape-entity

我使用grape(0.14.0)和grape-entity(0.5.0)在我的Rails(4.2.5)应用程序中创建XML API。每当我在Grape :: Entity类中指定显式的根元素时,XML响应就会被包含在不需要的根元素<hash>中。我怎么能摆脱它?

示例代码

# app/models/partner.rb
class Partner < ActiveRecord::Base
  #  company    :string
  #  name       :string
  #  secret     :string
end

# app/api/partners.rb
class Partners < Grape::API
  version 'v1', using: :path
  prefix :api
  format :xml

  resource :partners do
    get do
      present Partner.all, with: PartnerEntity
    end
  end
end

# app/api/partner_entity.rb
class PartnerEntity < Grape::Entity
  root 'partners', 'partner'
  expose :company
  expose :name
  expose :id
end

# Create a partner 
Partner.create!(name: 'A Name', company: 'A Company', secret: 'A secret')

结果

# GET /api/v1/partners.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<hash>
  <partners type="array">
    <partner>
      <company>A Company</company>
      <name>A Name</name>
      <id type="integer">1</id>
    </partner>
  </partners>
</hash>

在PartnerEntity中没有root的结果

# GET /api/v1/partners.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<partner-entities type="array">
  <partner-entity>
    <company>A Company</company>
    <name>A Name</name>
    <id type="integer">2</id>
  </partner-entity>
</partner-entities>

因为我需要明确地命名我的根元素,所以我不能没有root。

1 个答案:

答案 0 :(得分:0)

你找到这个帖子了吗? XML format is incorrect?

它包含一个想法,你可以覆盖它。 Use custom formetter to redefine XML root

 class API < Grape::API
   content_type :xml, 'application/xml'
   formatter :xml, Proc.new { |object|
     object[object.keys.first].to_xml :root => object.keys.first
 }