Class: RuboCop::Cop::Guardrails::ControllerInstanceVariables

Inherits:
Base
  • Object
show all
Includes:
VisibilityHelpers
Defined in:
lib/rubocop/cop/guardrails/controller_instance_variables.rb

Overview

Flags controller actions that assign too many instance variables.

Actions that set many instance variables are doing too much. Extract logic to the model layer, use a single rich object, or split into smaller controllers.

The ‘Max` option (default: 1) controls how many instance variable assignments are allowed per action. Assignments in `before_action` callbacks (private methods) are not counted.

Examples:

Max: 1 (default)

# bad
def show
  @card = Card.find(params[:id])
  @comments = @card.comments
  @related = @card.related_cards
end

# good — one object, the view navigates from there
def show
  @card = Card.find(params[:id])
end

Constant Summary collapse

MSG =
'Too many instance variables in action (%<count>d/%<max>d). ' \
'Let the view navigate from a single object.'

Instance Method Summary collapse

Instance Method Details

#on_def(node) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/rubocop/cop/guardrails/controller_instance_variables.rb', line 34

def on_def(node)
  if public_method?(node)
    count = ivar_assignment_count(node)
    max = max_assignments
    add_offense(node.loc.name, message: format(MSG, count: count, max: max)) if count > max
  end
end