Listing 3. pl-server.rb #!/usr/bin/ruby require 'rubygems' require 'net/http' require 'rexml/document' require 'xmlrpc/server' # ------------------------------------------------------------ # Load the translation cache # ------------------------------------------------------------ dictionary = { } puts "Loading cached translations" translation_file = 'translations.txt' if FileTest.exists?(translation_file) File.open(translation_file, "r").each do |line| (english, piglatin) = line.chomp.split('=') dictionary[english] = piglatin puts "'#{english}' => '#{piglatin}'" end else File.open(translation_file, 'w') do |line| end end # ------------------------------------------------------------ # XML-RPC # ------------------------------------------------------------ # Start an HTTP server on port 9000, to listen for clients server = XMLRPC::Server.new(port=9000, host='127.0.0.1') server.add_handler(name="atf.pl_sentence", signature=['array', 'array']) do |words| output = [ ] words.map {|word| word.to_s}.each do |word| # Have we already seen this word? Don't bother to translate it if dictionary.has_key?(word) puts "Grabbing translation of '#{word}' from the dictionary" output << dictionary[word] next end # If it's not in the cache, then go for it. piglatin = '' if word =~ /^[aeiou]/ piglatin << word piglatin << 'way' else piglatin = word[1..-1] piglatin << word[0] piglatin << 'ay' end puts "Translated '#{word}' => '#{piglatin}'" # Cache it puts "Trying to cache..." dictionary[word] = piglatin File.open(translation_file, 'a') {|f| f.puts "#{word}=#{piglatin}"} output << piglatin end output end server.serve