README

Path: README
Last Update: Fri Jun 09 17:04:25 EDT 2006

ResponseFrom

Mike Burns mike@mike-burns.com mike-burns.com

Update: This is mostly replaced by Rails 2.0's ActiveRecord#from_xml.

This plugin provides xml_response_from, the opposite of:

 respond_to { |want| want.xml { render(:xml => @user.to_xml) } }

More specifically, it sends a request to a server with the Accept HTTP header set to ‘application/xml’, then turns the response into an ActiveRecord object.

Fine-grained Control

There are a few ways to control this.

Class Mappings

The XML is turned into a class in a similar fashion that it is turned from a class into XML. Arrays are represented in the XML by a plural element name. Classes are represented by an element with the name of the class. Class attributes are represented by children elements of the class which have no non-text elements. Associations are represented by children elements with children elements. And so on, recursively.

The name of the XML element is the name of the class unless a mapping is used to override this. For example:

 class User < ActiveRecord::Base
   # fields: id, username, password
 end

 class ErrorUser < User
   def initialize(h)
   end
   def id
     raise RuntimeError.new('No such user')
   end
 end

 class AccountController < ActionController::Base
   def show
     @user = xml_response_from("#{URL}/account/show/#{params[:id]}",
                               { :error => ErrorUser })
   end
 end

Request Method and Data

The request method can be any HTTP method supported by Net::HTTP’s send_request method. Some methods support sending data. For example:

 class User < ActiveRecord::Base
   def self.authorize(login, password)
     xml_response_from("#{URL}/account/login",
                       { :error => ErrorUser },
                       :post,
                       "username=#{login}&password=#{password}")
   end
 end

Other Methods

A more generalized form of xml_response_from, named response_from, is also available. It doesn’t handle the XML but does handle the request and hands the response to a block. For an example of its use just look at xml_response_from:

 def xml_response_from(url, mappings = {}, method = :get, data = nil)
   response_from(url, method, data,
                 {'Accept' => 'application/xml'}) do |res|
     REXML::Document.new(res.body).root.from_xml(mappings)
   end
 end

Copyright 2006 Mike Burns

[Validate]