0

I'm using grape (0.14.0) with grape-entity (0.5.0) to create a XML API within my Rails (4.2.5) app. Whenever I specify an explicit root element within a Grape::Entity class the XML response gets wrapped in an unwanted root element <hash>. How can I get rid of it?

Example code

# 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')

Result

# 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>

Result without root in PartnerEntity

# 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>

Since I need to explicitly name my root elements I can't do without root.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Denny
  • 79
  • 4

1 Answers1

0

Did you find this thread? XML format is incorrect?

It contains with an idea which way you can override it. 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
 }
davidpgero
  • 11
  • 2