Blog

Using xmlrpc in sinatra

Added by Christoph Kappel about 7 years ago

During my experiments with buildbot I discovered the xmlrpc interface and think it would be a nice addition to the Sinatra based surserver - actually I don't like XML at all. Once you know how to get the XML document from a rack request the rest is trivial:

Sinatra

Numbers: on /off 1 require "rubygems" 
 2 require "sinatra" 
 3 require "xmlrpc/marshal" 
 4 
 5 helpers do
 6   def upper_case(args)
 7     XMLRPC::Marshal.dump_response(args[0].upcase)
 8   end
 9 end
10 
11 post "/xmlrpc" do
12   xml = @request.body.read
13 
14   if(xml.empty?)
15     error = 400
16     return
17   end
18 
19   # Parse xml
20   method, arguments = XMLRPC::Marshal.load_call(xml)
21   method = method.gsub(/([A-Z])/, '_ ').downcase
22 
23   # Check if method exists
24   if(respond_to?(method))
25     content_type("text/xml", :charset => "utf-8")
26     send(method, arguments)
27   else
28     error = 404
29   end
30 end

Basically we parse the incoming XML, dispatch the call to a matching handler method and send a XML response back.

Client

Numbers: on /off1 require "xmlrpc/client" 
2 
3 server = XMLRPC::Client.new("127.0.0.1", "/xmlrpc", 4567)
4 puts server.call("upper_case", ARGV[0])

The client is a mere call of the XMLRPC::Client API to get the result.

Output

1 % ruby xmlrpc.rb foobar
2 FOOBAR

Also available in: Atom RSS