25 Feb 2008

simple Ruby SOAP client

I am fairly new to Ruby and am quite amazed how simple and elegant this language can be. In particular I was surprised how simple it is to write a SOAP client in Ruby. Where in most programming languages even a simple SOAP client takes about two screenshots of code (if not more), a Ruby SOAP client can be boiled down to these few lines of code:


#soap_client.rb
require 'soap/wsdlDriver'

WSDL_URL="file://C:/hello_world.wsdl"

soap = SOAP::WSDLDriverFactory.new(WSDL_URL).create_rpc_driver("SOAPService", "SoapPort")

#invoke WSDL operation sayHi
result = soap.sayHi()
printf "Returned message reads: " + result + "\n"

#invoke WSDL operation greetMe
result = soap.greetMe("New Ruby User")
printf "Returned message reads: " + result + "\n"



In this code I am referring to a wsdl definition that defines two WSDL portType operations named sayHi() and greetMe() that both return a string.
In essence the code boils down to 4 lines of code that are of relevance. Of course this code is everything but object oriented and it is somewhat unfair to compare it against a properly implemented SOAP client written in other object oriented programming languages. Still this example is surprisingly simple and straight forward. I have used this code a number of times in order to quickly implement a SOAP test client. All you need to change is the name of the business method you actually want to invoke on (plus their arguments) and the location of the WSDL file. Thanks to Ruby you don't even need to recompile your changes.
Sure, most SOAP toolkits also provide a way to generate a fully working client and server without requiring you to write any code. Still the generated code is tied to the WSDL interface. Changes to one of the operation signatures typically require a regeneration of your test client/server.
Ruby rocks (and I am just starting to hit the tip of the iceberg)!

No comments: