Class: Twirp::ProtocPlugin::CodeGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/twirp/protoc_plugin/code_generator.rb

Instance Method Summary collapse

Constructor Details

#initialize(proto_file, relative_ruby_protobuf, options) ⇒ CodeGenerator

Returns a new instance of CodeGenerator.

Parameters:



15
16
17
18
19
# File 'lib/twirp/protoc_plugin/code_generator.rb', line 15

def initialize(proto_file, relative_ruby_protobuf, options)
  @proto_file = proto_file
  @relative_ruby_protobuf = relative_ruby_protobuf
  @options = options
end

Instance Method Details

#generateString

Returns the generated Twirp::Ruby code for the proto_file.

Returns:

  • (String)

    the generated Twirp::Ruby code for the proto_file



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/twirp/protoc_plugin/code_generator.rb', line 22

def generate
  output = StringIO.new
  output << <<~START
    # frozen_string_literal: true
    
    # Generated by the protoc-gen-twirp_ruby gem v#{VERSION}. DO NOT EDIT!
    # source: #{@proto_file.name}

    require "twirp"
    require_relative "#{@relative_ruby_protobuf}"

  START

  indent_level = 0
  modules = @proto_file.ruby_module.delete_prefix("::").split("::")

  modules.each do |mod|
    output << line("module #{mod}", indent_level)
    indent_level += 1
  end

  @proto_file.service.each_with_index do |service, index| # service: <Google::Protobuf::ServiceDescriptorProto>
    # Add newline between definitions when multiple are generated
    output << "\n" if index > 0

    if %i[service both].include?(@options[:generate])
      generate_service_class(output, indent_level, service)
    end

    if @options[:generate] == :both
      # Space between generated service and client when generating both
      output << "\n"

      generate_client_class_for_service(output, indent_level, service)
    elsif @options[:generate] == :client
      # When generating only the client, we can't use the `client_for` DSL.
      generate_client_class_standalone(output, indent_level, service)
    end
  end

  modules.each do |_|
    indent_level -= 1
    output << line("end", indent_level)
  end

  output.string
end