Class: RailsApiDocs::Inspectors::JsonRouteDetector

Inherits:
Object
  • Object
show all
Defined in:
lib/rails-api-docs/inspectors/json_route_detector.rb

Overview

Decides whether an endpoint should be considered “JSON-returning” for the ‘–api-only` filter on the install generator.

Decision logic for ‘call(controller:, action:)`:

1. If the controller's inheritance chain reaches `ActionController::API`
   (directly, or transitively via ApplicationController / a custom
   base controller) → true for every action.
2. Else if the action body contains a `render json: …` call (kwarg
   form or hash-rocket form, including inside `respond_to` blocks)
   → true.
3. Else → false.

‘:unknown` classifications (controller file missing, unresolvable parent constant) are strict — they DO NOT count as :api. Per-action render-json detection still runs if the file exists but inheritance is unresolvable.

Each controller file is parsed at most once per detector instance —the same Prism AST feeds both visitors, and the result hash is cached so the inheritance chain ApplicationController → ActionController::API is walked once even when 50 controllers inherit from it.

Known limitations:

- `render json:` inside a helper method called from the action is
  not detected (we don't follow method calls).
- `render template: "x", formats: :json` doesn't have a `json:`
  key in the call, so it's missed.
- Includes (`include SomeRenderingModule`) are not traversed.

Defined Under Namespace

Classes: JsonActionVisitor, SuperclassVisitor

Instance Method Summary collapse

Constructor Details

#initialize(root: nil) ⇒ JsonRouteDetector

Returns a new instance of JsonRouteDetector.



38
39
40
41
# File 'lib/rails-api-docs/inspectors/json_route_detector.rb', line 38

def initialize(root: nil)
  @root  = root || (defined?(Rails) && Rails.root ? Rails.root.to_s : ".")
  @cache = {}
end

Instance Method Details

#call(controller:, action:) ⇒ Object



43
44
45
46
47
# File 'lib/rails-api-docs/inspectors/json_route_detector.rb', line 43

def call(controller:, action:)
  profile = profile_for(controller)
  return true  if profile[:type] == :api
  profile[:json_actions].include?(action.to_s)
end

#profile_for(controller) ⇒ Object

Exposed for testing / debugging.



50
51
52
# File 'lib/rails-api-docs/inspectors/json_route_detector.rb', line 50

def profile_for(controller)
  @cache[controller] ||= analyze(controller)
end