Class: Docit::RouteInspector

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

Overview

Introspects Rails routes to map controller actions to HTTP paths and methods.

Constant Summary collapse

VALID_METHODS =
%w[get post put patch delete].freeze

Class Method Summary collapse

Class Method Details

.eager_load_controllers!Object

Eagerly loads controller classes so swagger_doc/use_docs macros run before spec generation.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/docit/route_inspector.rb', line 9

def self.eager_load_controllers!
  return if defined?(Rails).nil? || Rails.application.routes.nil?

  controller_paths = Rails.application.routes.routes.filter_map do |route|
    route.defaults[:controller]
  end.uniq

  controller_paths.each do |path|
    class_name = "#{path}_controller".camelize
    class_name.constantize
  rescue NameError
    # Skip controllers that can't be loaded (e.g., Rails internal routes)
  end
end

.routes_for(controller_name, action_name) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/docit/route_inspector.rb', line 24

def self.routes_for(controller_name, action_name)
  return [] if defined?(Rails).nil? || Rails.application.routes.nil?

  action = action_name.to_s

  # Convert Api::V1::AuthController to api/v1/auth
  controller_path = controller_name.underscore.delete_suffix("_controller").gsub("::", "/")

  Rails.application.routes.routes.filter_map do |route|
    next if route.defaults[:controller] != controller_path
    next if route.defaults[:action] != action

    verb = extract_verb(route)
    next if VALID_METHODS.exclude?(verb)

    { path: normalize_path(route.path.spec.to_s), method: verb }
  end
end