response_from: the opposite of respond_to render :xml

Update: This can be replaced, mostly, with Rails 2.0’s ActiveRecord#from_xml.

As I assured in a prior post, I spent today hacking on a plugin to make it easier to consume XML REST APIs. The result is the ResponseFrom plugin. It's the opposite of this:

 respond_to { |w| w.xml { render :xml => User.find_first } }

xml_response_from handles requesting XML then turning that XML into an ActiveRecord class. Well, it doesn't have to be an ActiveRecord class, it just needs to act like one at instantiation.

Anywho, the important bits:

So, to be clear, to install it you:

 ./script/plugin install http://myncre.com/svn/plugins/response_from/

And to use it you want to look at the documentation for xml_response_from.

My use for it is as follows: I use this in this User ActiveRecord to simulate the User.authenticate class method, plus some other similar methods. I'm in the midst of developing Land Brokr, which shares a database with MyNCRE. Rails isn't built for sharing databases between projects; instead, it expects you to communicate via a network API. To this end they've done wonders with respond_to and render's :xml argument. However, they left the other end empty: there's no clear, simple way to turn the XML back into something usable, or to even connect to the server (that I found). After doing it the long way for a few functions I decided to abstract it into a plugin. This cut about 30 lines out of my code and severly simplified my ActiveRecords.

The plugin infrastructure for Rails is pretty cool. Just remember to use script/generate to create your plugin; it'll save you a minute plus documentation hunting.

The other bit that I had to hunt down for a while was how to use the Inflector outside of Rails proper. Thanks, Martin, for the clear write-up.

I'm open to constructive criticism on this, my first Rails plugin.

Advertisements

One Comment

  1. Brian Hutchison
    Posted February 11, 2007 at 2:53 am | Permalink

    I think this is a great idea. I see many examples of using Rails to generate XML and very few showing how to consume XML resources. Bravo.


3 Trackbacks/Pingbacks

  1. […] For work I developed the RepsonseFrom plugin for Ruby on Rails. Since I've released it to the public I figure I should probably write about it in my hobby blog. That's this. […]

  2. […] I admit, I believed it when DHH said that Rails apps should communicate via REST if they want access to a shared database. I bought into the hype and even wrote a plugin to make this easier. […]

  3. […] response_from: the opposite of respond_to render :xml « Mike Burns, Coder To this end they’ve done wonders with respond_to and render’s :xml argument. However, they left the other end empty: there’s no clear, simple way to turn the XML back into something usable, or to even connect to the server (that I found). (tags: ruyb rails xml) […]

%d bloggers like this: