- Proper mono version
[tberman-thrift.git] / tutorial / rb / RubyServer.rb
blob684d05a4a5ae54090c8011eeda31a7b2e6be2485
1 #!/usr/bin/env ruby
3 $:.push('../gen-rb')
4 $:.unshift '../../lib/rb/lib'
6 require 'thrift'
7 require 'thrift/protocol/binaryprotocol'
8 require 'thrift/server/tserver'
10 require 'Calculator'
11 require 'shared_types'
13 class CalculatorHandler
14   def initialize()
15     @log = {}
16   end
18   def ping()
19     puts "ping()"
20   end
22   def add(n1, n2)
23     print "add(", n1, ",", n2, ")\n"
24     return n1 + n2
25   end
27   def calculate(logid, work)
28     print "calculate(", logid, ", {", work.op, ",", work.num1, ",", work.num2,"})\n"
29     if work.op == Operation::ADD
30       val = work.num1 + work.num2
31     elsif work.op == Operation::SUBTRACT
32       val = work.num1 - work.num2
33     elsif work.op == Operation::MULTIPLY
34       val = work.num1 * work.num2
35     elsif work.op == Operation::DIVIDE
36       if work.num2 == 0
37         x = InvalidOperation.new()
38         x.what = work.op
39         x.why = "Cannot divide by 0"
40         raise x
41       end
42       val = work.num1 / work.num2
43     else
44       x = InvalidOperation.new()
45       x.what = work.op
46       x.why = "Invalid operation"
47       raise x
48     end
50     entry = SharedStruct.new()
51     entry.key = logid
52     entry.value = "#{val}"
53     @log[logid] = entry
55     return val
57   end
59   def getStruct(key)
60     print "getStruct(", key, ")\n"
61     return @log[key]
62   end
64   def zip()
65     print "zip\n"
66   end
68 end
70 handler = CalculatorHandler.new()
71 processor = Calculator::Processor.new(handler)
72 transport = Thrift::ServerSocket.new(9090)
73 transportFactory = Thrift::BufferedTransportFactory.new()
74 server = Thrift::SimpleServer.new(processor, transport, transportFactory)
76 puts "Starting the server..."
77 server.serve()
78 puts "done."