Class: Skit::JsonSchema::CodeGenerator

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/skit/json_schema/code_generator.rb

Instance Method Summary collapse

Constructor Details

#initialize(module_definition, config) ⇒ CodeGenerator

Returns a new instance of CodeGenerator.



10
11
12
13
# File 'lib/skit/json_schema/code_generator.rb', line 10

def initialize(module_definition, config)
  @module_definition = module_definition
  @config = config
end

Instance Method Details

#generateObject



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
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
# File 'lib/skit/json_schema/code_generator.rb', line 16

def generate
  parts = []

  # Header
  parts << "# typed: #{@config.typed_strictness}"
  parts << "# frozen_string_literal: true"
  parts << ""
  parts << "# This file is autogenerated by skit"
  parts << "# DO NOT EDIT MANUALLY"
  parts << ""
  parts << 'require "sorbet-runtime"'
  parts << 'require "skit"' if const_types?

  module_parts = @config.module_name&.split("::")
  indent_level = module_parts&.length || 0

  if module_parts
    parts << ""
    module_parts.each_with_index do |module_part, index|
      parts << "#{"  " * index}module #{module_part}"
    end
  end

  # Enum types
  @module_definition.enum_types.each do |enum_type|
    parts << ""
    parts << generate_enum_class(enum_type, indent_level)
  end

  # Const types
  @module_definition.const_types.each do |const_type|
    parts << ""
    parts << generate_const_class(const_type, indent_level)
  end

  # Nested structs
  @module_definition.nested_structs.each do |nested_struct|
    parts << ""
    parts << generate_single_struct(nested_struct, indent_level)
  end

  # Main struct
  parts << ""
  parts << generate_single_struct(@module_definition.root_struct, indent_level)

  module_parts&.reverse&.each_with_index do |_, index|
    parts << "#{"  " * (T.must(module_parts).length - index - 1)}end"
  end

  parts.join("\n")
end