12. Using XML-RPC with Ruby

(This section of the XML-RPC HOWTO was generously provided by Michael Neumann.)

Ruby is an object-oriented scripting language. It already has a major following in Japan, and it's becoming popular elsewhere.

To use XML-RPC with Ruby, you must first install Yoshida Masato's xmlparser module (a wrapper for James Clark's expat parser). This can be found at the Ruby Application Archive.

Then, you must install xmlrpc4r using the following commands:

bash$ tar -xvzf xmlrpc4r-1_2.tar.gz
bash$ cd xmlrpc4r-1_2
bash$ su root -c "ruby install.rb"

12.1. A Ruby Client

Here's a simple Ruby client:

require "xmlrpc/client"

# Make an object to represent the XML-RPC server.
server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")

# Call the remote server and get our result
result = server.call("sample.sumAndDifference", 5, 3)

sum = result["sum"]
difference = result["difference"]

puts "Sum: #{sum}, Difference: #{difference}"

12.2. A Ruby Server

Here's a simple Ruby server:

require "xmlrpc/server"

s = XMLRPC::CGIServer.new

s.add_hanlder("sample.sumAndDifference") do |a,b|
  { "sum" => a + b, "difference" => a - b }


This could also have been written as follows:

require "xmlrpc/server"

s = XMLRPC::CGIServer.new

class MyHandler
  def sumAndDifference(a, b)
    { "sum" => a + b, "difference" => a - b }

s.add_handler("sample", MyHandler.new)

To run either server in standalone mode, replace the second line of code with the following:

s = XMLRPC::Server.new(8080)