Tuesday, August 7, 2007

RESTful Rails Angst

I've been working with Rails to provide RESTful services to a Flex application recently and a number of issues have come up that people need to know about dern it.

Today's story entails a battle with Rails' scaffold_resource. The RESTful generator makes a noble effort to create RESTful controllers. However, a few minor issues pop-up that need repairing in the current incarnation of the generator.

The most glaring issue is that the default code doesn't handle ActiveRecord find errors gracefully. For example, if I have a FoosController servicing requests to "/foos/1.xml" and that model :id=1 doesn't exist, the default FoosController will throw a RecordNotFound which up the call stack results in a 500 error being returned to the client. This, is unfortunately not "RESTful" as they say. The correct behavior would be to return a 404 indicating that the desired resource does not exist, not that the server could not handle the request. Adding this behavior is not difficult, but it's somewhat tedious in that each generated controller exposes four find calls that can fail in this way.

Additionally, as Peter Armstrong's solid PDF-only book on Flexible Rails points out, the default implementation of to_xml used throughout the controller is quite painful for certain clients. Most programming languages don't allow "-" in member names and as such, mapping tools that attempt to make XML traversal easier by exposing the XML structure as a choke on the default XML marshaling. As Peter points out, you can change this behavior by adding the ":dasherize" option but again, this is all over RESTful Rails controllers.

I could fix both of these through some hacking on the Rails distro, but then I have to remember to keep my changes across upgrades. Another option would likely entail injecting some app-specific base classes into the hierarchy, again not an idea I'm crazy about. If I come up with a better approach, I'll post it here. Or maybe back as a patch :)

No comments: