martes, 2 de septiembre de 2008

Clientes WS en Ruby

Ruby on rails nos permite crear clientes de WS basados en arquitecturas REST, SOAP y XML-RPC. Aparentemente es muy sencillo y requiere algunas bibliotecas que se cargan automáticamente con Rails (por ejemplo: clientsCGI, NET, REXML, Soap4r, XSD, and XML-RPCare).
Luego de haber instalado InstantRails pude explorar un poco la estructura de directorios de las aplicaciones web de ruby on rails, los fuentes se colocan en la ruta ...\\rails_apps\\app\ donde se recomienda que agrupe archivos con una funcionalidad similar (i.e. controllers, views, helpers).
Estoy utilizando unos ejemplos de los libros que mencioné mi post pasado para familiarizarme con el framework. A continuación, y a manera de ilustración, copio el código necesario para consultar un WS de yahoo con REST:

...
Once you have your developer key, we're ready to build a simple controller (saved as code_controller.rb in the app/controllers folder):

class CodeController < ApplicationController
def yahootest
query = CGI.escape("SEARCH TEXT") # URL-encoded search value
yahookey = "YOUR YAHOO DEVELOPER KEYs # Your Yahoo! dev key
url = "http://api.search.yahoo.com/" + # The URL to the Yahoo!
"WebSearchService/V1/webSearch?" + # Search service
"appid=#{yahookey}&query=#{query}" +
"&results=3&start=1"
result = Net::HTTP.get(URI(url)) # make the actual HTTP request
@doc = REXML::Document.new result # turn the results into a
# REXML document
end
end

Then we build a view that displays the search results in a simple view. Save the following code in a file called yahootest.rhtml in the app/code/views folder:

<% @doc.root.each_element do |res| %>
<b>Title:</b> <%= res[0].text.to_s %><br>
<b>Summary:</b> <%= res[1].text.to_s %><br>
<b>Link:</b> <a href="<%= res[2].text.to_s %>"><%= res[2].text.to_s %></a>
<br><br>
<% end %>

Believe it or not, we're done. In just a few short lines of code, we've built a complete web service client for your Rails application. You should be able to test your application with your local version of Webrick at the URL http://localhost:3000/code/yahootest.
...

Sencillo, vamos a ver como me va... =P

1 comentario:

Andres Arias dijo...

Hola Edgar

Gracias por el aporte! Sigan adelante