Class: Calculator

Inherits:
Math::Math::Service show all
Defined in:
src/ruby/bin/math_server.rb

Overview

The Math::Math

module occurs because the service has the same name as its

package. That practice should be avoided by defining real services.

Instance Method Summary collapse

Methods included from GRPC::GenericService

included, underscore

Instance Method Details

#div(div_args, _call) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
# File 'src/ruby/bin/math_server.rb', line 97

def div(div_args, _call)
  if div_args.divisor.zero?
    # To send non-OK status handlers raise a StatusError with the code and
    # and detail they want sent as a Status.
    fail GRPC::StatusError.new(GRPC::Status::INVALID_ARGUMENT,
                               'divisor cannot be 0')
  end

  Math::DivReply.new(quotient: div_args.dividend / div_args.divisor,
                     remainder: div_args.dividend % div_args.divisor)
end

#div_many(requests) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'src/ruby/bin/math_server.rb', line 126

def div_many(requests)
  # requests is an lazy Enumerator of the requests sent by the client.
  q = EnumeratorQueue.new(self)
  t = Thread.new do
    begin
      requests.each do |req|
        GRPC.logger.info("read #{req.inspect}")
        resp = Math::DivReply.new(quotient: req.dividend / req.divisor,
                                  remainder: req.dividend % req.divisor)
        q.push(resp)
        Thread.pass  # let the internal Bidi threads run
      end
      GRPC.logger.info('finished reads')
      q.push(self)
    rescue StandardError => e
      q.push(e)  # share the exception with the enumerator
      raise e
    end
  end
  t.priority = -2  # hint that the div_many thread should not be favoured
  q.each_item
end

#fib(fib_args, _call) ⇒ Object



116
117
118
119
120
121
122
123
124
# File 'src/ruby/bin/math_server.rb', line 116

def fib(fib_args, _call)
  if fib_args.limit < 1
    fail StatusError.new(Status::INVALID_ARGUMENT, 'limit must be >= 0')
  end

  # return an Enumerator of Nums
  Fibber.new(fib_args.limit).generator
  # just return the generator, GRPC::GenericServer sends each actual response
end

#sum(call) ⇒ Object



109
110
111
112
113
114
# File 'src/ruby/bin/math_server.rb', line 109

def sum(call)
  # the requests are accesible as the Enumerator call#each_request
  nums = call.each_remote_read.collect(&:num)
  sum = nums.inject { |s, x| s + x }
  Math::Num.new(num: sum)
end