12. Ruby로 XML-RPC 사용하기

(이 장의 대부분은 Michael Neumann이 썼다.)

Ruby는 객체지향적인 스크립트 언어다. 이미 일본에서는 프로그래밍의 주류를 이루고 있으며, 그 외의 곳으로도 확대되어 가고 있다.

Ruby로 XML-RPC를 사용하기 위해서는 먼저 Yoshida Masato의 xmlparser 모듈(James Clark의 expat 파서의 루비용 래퍼)을 먼저 설치해야 한다. 이 모듈은 Ruby Application Archive에서 찾을 수 있다.

xmlrpc4r 모듈을 다음과 같이 설치하라:

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

12.1. Ruby 클라이언트

다음은 간단한 Ruby 클라이언트이다:

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. Ruby 서버

다음은 간단한 Ruby 서버이다:

require "xmlrpc/server"

s = XMLRPC::CGIServer.new

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

s.serve

위의 코드는 다음과 같이 작성할 수도 있다:

require "xmlrpc/server"

s = XMLRPC::CGIServer.new

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

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

CGI 기반의 서버 대신 독립 서버로 실행하려면 두번째 줄을 다음과 같이 바꾸면 된다:

s = XMLRPC::Server.new(8080)