This post originated from an RSS feed registered with Ruby Buzz
by Jamis Buck.
Original Post: Web services, Rails-style
Feed Title: the buckblogs here
Feed URL: http://weblog.jamisbuck.org/blog.cgi/programming/index.rss
Feed Description: Jamis Buck's corner of the blogging universe. Mostly about ruby, but includes ramblings on a variety of topics.
What that says is, “if the client wants HTML in response to this action, just respond as we would have before, but if the client wants XML, return them the list of people in XML format.” (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
Now, let’s suppose you have an action that adds a new person, optionally creating their company (by name) if it does not already exist. Without web-services, it might look like this:
It was simple enough that I also added RJS support here. If the client wants HTML, we just redirect them back to the person list. If they want Javascript (wants.js), then it is an RJS request and we render the RJS template associated with this action. Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also include the person’s company in the rendered XML, so you get something like this:
This is because the incoming XML document (if a web-service request is in process) can only contain a single root-node. So, we have to rearrange things so that the request looks like this (url-encoded):
In other words, we make the request so that it operates on a single entity—a person. Then, in the action, we extract the company data from the request, find or create the company, and then create the new person with the remaining data.
Note that you can define your own XML parameter parser which would allow you to describe multiple entities in a single request (i.e., by wrapping them all in a single root note), but if you just go with the flow and accept Rails’ defaults, life will be much easier.