We have a client who insists on our API providing XML, so we're fulfilling that.
The XML root element name is hard-coded to data in the Graphiti renderer which is not ideal since there is a child element inside also named data.
We have worked around this, but it would be nice to be able to specify the root element name where the Graphiti renderer could use it.
Looking at the source, here is where the magic happens, best I can tell:
|
render(self.class.hash_renderer(@proxy)).to_xml(root: :data) |
Right now this is a simplified version of what our work-around looks like:
# app/controllers/api/my_controller.rb
class Api::MyController < Api::ApplicationController
def index
resources = MyResource.all(params)
respond_to do |format|
format.json { render(json: resources) }
format.jsonapi { render(jsonapi: resources) }
format.xml { render(xml: pretty_xml(resources)) }
end
end
# By default when a Graphiti resource proxy list is resolved to XML it looks like this:
#
# <data>
# <data type="array">
# <datum>
# ...
# </datum>
# </data>
# <meta>
# ...
# </meta>
# </data>
#
#
# Instead we want it to look like this:
#
# <root>
# <data type="array">
# <datum>
# ...
# </datum>
# </data>
# <meta>
# ...
# </meta>
# </root>
def pretty_xml(resource_proxy)
json = resource_proxy.to_json
JSON.parse(json).to_xml(root: :root)
end
end
We have a client who insists on our API providing XML, so we're fulfilling that.
The XML root element name is hard-coded to
datain the Graphiti renderer which is not ideal since there is a child element inside also nameddata.We have worked around this, but it would be nice to be able to specify the root element name where the Graphiti renderer could use it.
Looking at the source, here is where the magic happens, best I can tell:
graphiti/lib/graphiti/renderer.rb
Line 37 in 0389e50
Right now this is a simplified version of what our work-around looks like: