Donnerstag, 14. November 2013

Ruby, Savon with WSDL, Nokogiri

A very simple example on how to call a SOAP Web service with Ruby and Savon. The call returns a XML document. Nokogiri helps to extract the data we're interested in.
#!ruby
# make sure we use version 2.x of Savon
gem 'savon', '~> 2.0'
require 'savon'
require 'nokogiri'
# create the client, switch on nice logging
clnt = Savon.client(
wsdl: 'http://www.webservicex.net/stockquote.asmx?wsdl',
log: true,
log_level: :debug,
pretty_print_xml: true
)
# look up a ticker symbol or use Open Text's NASDAQ
symbol = ARGV[0] || "OTEX"
# call the service
response = clnt.call(:get_quote, message: { symbol: symbol.upcase } )
result = response.to_hash[:get_quote_response][:get_quote_result]
# this result is in XML form, let's take it apart
xml = Nokogiri::XML(result)
# print a nicely formatted XML document
print xml.to_xml(:indent => 4)
# just want to know the last price of the equity
quote = xml.at_css('Last').text.strip
d = xml.at_css('Date').text
t = xml.at_css('Time').text
# the date comes in US format mm/dd/yy
date = DateTime.strptime("#{d} #{t}", "%m/%d/%Y %I:%M%p")
print "Date: ", date.strftime("%d-%b-%Y"), "\n"
print "Last quote: ", quote, "\n"