Class: OpenapiSlicer

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

Overview

OpenapiSlicer is a tool that slices an OpenAPI spec based on a regular expression, and filters out necessary paths and components, ensuring that all dependent components (schemas, parameters, etc.) are included.

Constant Summary collapse

VERSION =

The current version of the OpenapiSlicer

"0.2.2"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path:, prettify: true) ⇒ OpenapiSlicer

Initializes the OpenapiSlicer.

Parameters:

  • file_path (String)

    the path to the OpenAPI spec file (JSON or YAML)

  • prettify (Boolean) (defaults to: true)

    (true) prettify JSON if true, otherwise compress JSON

Raises:

  • (RuntimeError)

    if the file is not a JSON or YAML file



23
24
25
26
27
28
29
30
31
# File 'lib/openapi_slicer.rb', line 23

def initialize(file_path:, prettify: true)
  raise "Invalid file type. Only JSON and YAML are supported." unless file_path.match?(/\.(json|ya?ml)$/)

  @file_path = file_path
  @prettify = prettify
  @spec = load_spec(file_path)
  @components = {}
  @tags = Set.new
end

Instance Attribute Details

#prettifyObject (readonly)

Returns the value of attribute prettify.



16
17
18
# File 'lib/openapi_slicer.rb', line 16

def prettify
  @prettify
end

#specHash

Returns the OpenAPI specification loaded from the file.

Returns:

  • (Hash)

    the OpenAPI specification loaded from the file



15
16
17
# File 'lib/openapi_slicer.rb', line 15

def spec
  @spec
end

Instance Method Details

#export(regex, target_file) ⇒ Object

Exports the filtered OpenAPI spec to a file.

Parameters:

  • regex (Regexp)

    the regular expression to match against the paths

  • target_file (String)

    the file path to write the filtered spec to



48
49
50
51
52
53
54
55
56
57
# File 'lib/openapi_slicer.rb', line 48

def export(regex, target_file)
  result = filter(regex)
  File.open(target_file, "w") do |f|
    if target_file.match?(/\.json$/)
      f.write(prettify ? JSON.pretty_generate(result) : result.to_json)
    else
      f.write(result.to_yaml)
    end
  end
end

#filter(regex) ⇒ Hash

Filters the OpenAPI spec paths based on a regular expression and extracts the necessary components and tags.

Parameters:

  • regex (Regexp)

    the regular expression to match against the paths

Returns:

  • (Hash)

    the filtered OpenAPI spec with paths and dependencies



38
39
40
41
42
# File 'lib/openapi_slicer.rb', line 38

def filter(regex)
  paths = @spec["paths"].select { |path, _| path.match?(regex) }
  dependencies = extract_dependencies(paths)
  slice_spec(paths, dependencies)
end