| Path: | lib/response_from.rb |
| Last Update: | Fri Jun 09 16:20:52 EDT 2006 |
Takes a full URL, the method to use (must be one of :get, :post, :put, :delete, :head, :lock, :mkcol, :move, :options, :propfind, :proppatch, :trace, or :unlock), any data to pass over a POST or PUT request, and a hash of headers to send. The optional block takes a response. The result is either the result of the block or, if none is given, the result of the request (a HTTPResponse).
Raises a RuntimeError if the result of the request is anything besides a HTTPSuccess.
For example:
response_from('http://localhost:3000/account/login', :post,
{ :username => 'mary', :password => 'god' },
{'Accept' => 'application/xml') do |res|
x = REXML::Document.new(res.body).root
x.get_elements('user')[0].get_elements('id').text.to_i
end
# File lib/response_from.rb, line 21
21: def response_from(url, method = :get, data = nil, headers = nil)
22: unless [:get,:post,:put,:delete,:head,:lock,:mkcol,:move,:options,
23: :propfind,:proppatch,:trace,:unlock].include?(method)
24: raise ArgumentError.new('Unsuppored method')
25: end
26: uri = URI.parse(url)
27: net = Net::HTTP.new(uri.host, uri.port)
28: res = net.send_request(method.to_s.capitalize, uri.path, data, headers)
29: if res.is_a?(Net::HTTPSuccess)
30: if block_given?
31: result = yield(res)
32: else
33: result = res
34: end
35: else
36: raise RuntimeError.new("#{method} produced #{res.class}")
37: end
38: return result
39: end
Takes a full URL, a hash for mapping root nodes to classes, the request method, and any data for a POST or PUT method. Produces a class with the same name as the root node of the XML or the class specified in the mapping.
The mapping is a hash from symbol to class.
A root node is the root node of the XML document, the children of a pluralized root node, or a child element of a root node which has children elements.
If a root node is plural this produces an array; otherwise this produces the class with the same name, unless the mapping contains a key with the same name as the root node.
Examples:
user = xml_response_from('http://localhost:3000/account/login',
{ :user => RemoteUser },
:post,
'username=mary&password=god')
houses = xml_response_from("http://localhost:3000/houses/mine?id=#{user.id}")
# File lib/response_from.rb, line 62
62: def xml_response_from(url, mappings = {}, method = :get, data = nil)
63: response_from(url,method,data,{'Accept' => 'application/xml'}) do |res|
64: REXML::Document.new(res.body).root.from_xml(mappings)
65: end
66: end