Response From plugin

Plugin details

This plugin provides xml_response_from, the opposite of "respond_to". 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.

Repositoryhttp://myncre.com/svn/plugins/response_from/ Author Mike Burns Tags http, response LicenseMIT

Documentation

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

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

Further Documentation

There is currently no advanced documentation for this plugin.

New documentation

Edit plugin | (0 older versions) | Last edited by: hardway, 7 months ago