Class: GrpcRequiredAnnotator::Required

Inherits:
Object
  • Object
show all
Defined in:
lib/grpc_required_annotator/required.rb

Defined Under Namespace

Classes: NotExistFieldError, UnsupportedTypeError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fields) ⇒ Required

Returns a new instance of Required.



10
11
12
# File 'lib/grpc_required_annotator/required.rb', line 10

def initialize(fields)
  @fields = fields
end

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



8
9
10
# File 'lib/grpc_required_annotator/required.rb', line 8

def fields
  @fields
end

Instance Method Details

#validate!(request) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/grpc_required_annotator/required.rb', line 14

def validate!(request)
  @fields.each do |field|
    unless request.respond_to?(field)
      raise NotExistFieldError.new("#{field} does not exist in #{request.class}")
    end

    value = request.public_send(field)

    case value
    when Integer
      raise GRPC::InvalidArgument.new("`#{field}` is required") if value == 0
    when String
      raise GRPC::InvalidArgument.new("`#{field}` is required") if value == ""
    when Google::Protobuf::FieldMask
      raise GRPC::InvalidArgument.new("`#{field}` is required") if value.paths.empty?
    when Google::Protobuf::RepeatedField
      raise GRPC::InvalidArgument.new("`#{field}` is required") if value.empty?
    when Symbol
      raise GRPC::InvalidArgument.new("`#{field}` is required") if value.to_s.include?("UNSPECIFIED") # https://developers.google.com/protocol-buffers/docs/style#enums
    when nil
      raise GRPC::InvalidArgument.new("`#{field}` is required")
    else
      raise UnsupportedTypeError.new("#{value.class} is not supported. value is #{value}")
    end
  end

  true
end