Class: GrapeOpenapi3::PathNormalizer

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

Overview

Converts a Grape route path to an OpenAPI 3.0 path string.

"/v2/lessons/:id(.:format)"  →  "/v2/lessons/{id}"
"/v2/users"                  →  "/v2/users"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(grape_path, version: nil) ⇒ PathNormalizer

Returns a new instance of PathNormalizer.



13
14
15
16
# File 'lib/grape_openapi3/path_normalizer.rb', line 13

def initialize(grape_path, version: nil)
  @path    = grape_path.to_s
  @version = version
end

Class Method Details

.call(grape_path, version: nil) ⇒ Object



9
10
11
# File 'lib/grape_openapi3/path_normalizer.rb', line 9

def self.call(grape_path, version: nil)
  new(grape_path, version: version).call
end

Instance Method Details

#callObject



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/grape_openapi3/path_normalizer.rb', line 18

def call
  result = @path
    .gsub(/\(.*?\)/, "")     # remove optional segments: (.:format)
    .gsub(/:(\w+)/, '{\1}')  # :id → {id}
    .gsub(%r{/+$}, "")       # strip trailing slashes

  # Replace Grape's {version} placeholder with the real version string
  # e.g. /api/{version}/products → /api/v1/products
  result = result.gsub("{version}", @version) if @version

  result = "/#{result}" unless result.start_with?("/")
  result.empty? ? "/" : result
end