Class: ApiRegulator::OpenApiGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/api_regulator/open_api_generator.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_definitions, version:) ⇒ OpenApiGenerator

Returns a new instance of OpenApiGenerator.



23
24
25
26
# File 'lib/api_regulator/open_api_generator.rb', line 23

def initialize(api_definitions, version:)
  @api_definitions = api_definitions
  @version = version
end

Instance Attribute Details

#api_definitionsObject (readonly)

Returns the value of attribute api_definitions.



19
20
21
# File 'lib/api_regulator/open_api_generator.rb', line 19

def api_definitions
  @api_definitions
end

#final_schemaObject (readonly)

Returns the value of attribute final_schema.



21
22
23
# File 'lib/api_regulator/open_api_generator.rb', line 21

def final_schema
  @final_schema
end

#versionObject (readonly)

Returns the value of attribute version.



20
21
22
# File 'lib/api_regulator/open_api_generator.rb', line 20

def version
  @version
end

Class Method Details

.generate(api_definitions, version: ApiRegulator.configuration.default_version) ⇒ Object



5
6
7
8
# File 'lib/api_regulator/open_api_generator.rb', line 5

def self.generate(api_definitions, version: ApiRegulator.configuration.default_version)
  generator = new(api_definitions, version: version)
  generator.generate
end

.schema_file_path(version: ApiRegulator.configuration.default_version) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/api_regulator/open_api_generator.rb', line 10

def self.schema_file_path(version: ApiRegulator.configuration.default_version)
  file_name = version.present? ? "openapi-#{version}.json" : "openapi.json"
  [
    ApiRegulator.configuration.docs_path,
    "/",
    file_name
  ].compact.join
end

Instance Method Details

#generateObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/api_regulator/open_api_generator.rb', line 28

def generate
  @final_schema = {
    openapi: '3.1.0', # Explicitly target OpenAPI 3.1.0
    info: {
      title: ApiRegulator.configuration.app_name,
      description: 'Generated by ApiRegulator'
    },
    servers: ApiRegulator.configuration.servers,
    paths: {}
  }
  final_schema[:info][:version] = version if version.present?

  add_components
  add_security
  add_webhooks

  api_definitions.each do |api|
    add_api_to_schema(api)
  end

  schema_path = self.class.schema_file_path(version: version)
  File.write(schema_path, JSON.pretty_generate(final_schema))
  puts "OpenAPI schema generated: #{schema_path}"
end