On Friday, July 20, 2012 03:57:55 PM Martyn Taylor wrote:
Hi gents,
There has been a few people raising similar questions around why are we not using the default rails renders and instead are using templates to render such things as xml. I've put together my reasoning on choosing this approach below:
I assume most people are aware that render :xml simply using a models to_xml method to parse the model.
There are a few issues with to_xml.
- to_xml uses elements for everything. In our API we use attributes
for special fields on our resources. These special fields are used to identify the resource and give its location. i.e. href and id.
We could extend to_xml to handle this for us. But there are some other issues.
To render href we need url helpers too... and these really do not belongs into the model.
- When returning lists and nested resources. For example:
<provider> <provider_account /> </provider>
or
<providers> <provider id='1' href='' /> <provider id='2' href='' /> </providers>
We do not want to return the full resource just a reference to it. This is to reduce the size of response body. to_xml will simply call to_xml on nested resources resulting in full resource representation.
- When rendering resources we only want to list its direct children,
not grandchildren. This is again to avoid sending whole object graphs in response bodies. Using to_xml will result in every resource in the graph being rendered.
- Templates are much more flexible.
All of the issues I described above could be implemented by overriding the to_xml method. Though it would get a little complicated.
Templates are much easier to maintain and update. In addition, using templates gives us more control on what we return on a individual model basis. For example we could have logic in our templates that say things like.
If STATUS == "Complete" then #don't return progress. etc....
To summarize. Yes you can use to_xml which is the standard way to render things like xml, json in rails. But there is a significant amount of work in implementing bespoke methods to make it work the way we need it to. Templates are much more flexible and are easier to implement. The downside of templates is that we have more files to maintain. But there is nothing complicated about templates they are extremely trivial.