Saturday, February 2, 2008

Spiffy Resource: ActiveResource View/Form-Handler Initializer

A lot of people think that you can just treat ActiveResource models and ActiveRecord models as entirely identical things, with only one difference - that one is loaded from the database and the other is loaded from the network. That isn't the case, but it's a very common misconception, and the reason it's such a common misconception is because that if ActiveResource did work that way it'd be incredibly useful.

It's not that hard, however, to make it true. A little while back I released Snazzy Resource, which gives you one piece of the puzzle. This plugin, Spiffy Resource, gives you another piece:

script/plugin \

Spiffy Resource is based on a strategy I described a few months ago: build an ActiveResource schema dumper. Part of the stumbling block with using ActiveResource models as if they were ActiveRecord models is that ActiveRecord models add on attribute methods at definition, based on a schema dump from the database, and ActiveResource models don't.

In the blog post late last summer I described writing a Rails controller action to dump the schema across the network as XML, and having your ActiveResource app receive that schema and add on attribute methods the same way. This plugin doesn't quite do that, because this time, my client programmer is writing code against a Web service that doesn't come from a Rails app. We could very likely have it dump an XSD, and that could be more portable for a larger number of possible uses, but it was much much simpler just to define a YAML file with, essentially, a schema, and have the plugin load that schema and add attribute methods accordingly.

The win, of course, is that it works for web services that come from Rails apps and web services that don't; and indeed that it works whether or not you have any control at all over the internals of the service. The downside is you have to generate the YAML manually. (However, it should be very easy to write something which parses a Rails db schema dump and turns it into YAML.)

Combine Snazzy Resource with Spiffy Resource, and you should have not only one well-dressed resource, but also a nice, easy, plug-and-play experience developing Rails apps with ActiveResource models.