Class: RailsOpenapiGen::Parsers::RoutesParser

Inherits:
Object
  • Object
show all
Defined in:
lib/rails-openapi-gen/parsers/routes_parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(file_checker: File.method(:exist?)) ⇒ RoutesParser

Initialize with optional file existence checker for testability

Parameters:

  • file_checker (#call) (defaults to: File.method(:exist?))

    Callable that checks if file exists (defaults to File.exist?)



10
11
12
# File 'lib/rails-openapi-gen/parsers/routes_parser.rb', line 10

def initialize(file_checker: File.method(:exist?))
  @file_checker = file_checker
end

Instance Method Details

#parseArray<Hash>

Parses Rails application routes to extract route information

Returns:

  • (Array<Hash>)

    Array of route hashes with method, path, controller, action, and name



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
# File 'lib/rails-openapi-gen/parsers/routes_parser.rb', line 16

def parse
  routes = []

  Rails.application.routes.routes.each do |route|
    next unless route.defaults[:controller] && route.defaults[:action]
    next if route.respond_to?(:internal?) ? route.internal? : route.instance_variable_get(:@internal)

    # Skip Rails internal and asset routes
    controller_name = route.defaults[:controller]
    next if controller_name.to_s.start_with?('rails/')
    next if controller_name.to_s == 'assets'

    # Extract HTTP method from route.verb (which can be a Regexp like /^GET$/)
    raw_method = route.verb.is_a?(Array) ? route.verb.first : route.verb
    method = if raw_method.is_a?(Regexp)
               raw_method.source.gsub(/[\^$()?\-:mix]/, '')
             else
               raw_method.to_s
             end
    # Remove format suffix patterns more robustly
    path = route.path.spec.to_s
                .gsub(/\(\.:format\)$/, "")              # Standard format pattern
                .gsub(/\(\.\*format\)$/, "")             # Wildcard format pattern
                .gsub(/\(\.[\w|*]*\)$/, "") # Complex format patterns like (.json|.xml|.csv)
                .gsub(/\(\.[^)]*\)$/, "")
    controller = infer_controller_from_route(route)
    action = route.defaults[:action]

    routes << {
      verb: method,           # Test expects 'verb'
      method: method,         # Keep for backward compatibility
      path: path,
      controller: controller,
      action: action,
      name: route.name
    }
  end

  routes
end