Class: RuboCop::Cop::Guardrails::ShallowJob

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

Overview

Flags job ‘perform` methods with too many statements.

Jobs should be thin wrappers that delegate to model methods. A ‘perform` method with many statements is a sign that business logic has leaked into the job layer.

The ‘MaxStatements` option (default: 2) controls the threshold.

Examples:

MaxStatements: 2 (default)

# bad
class NotifyRecipientsJob < ApplicationJob
  def perform(card)
    recipients = card.watchers - [card.creator]
    recipients.each do |user|
      NotificationMailer.card_updated(user, card).deliver_later
    end
    card.update!(notified_at: Time.current)
  end
end

# good — delegate to the model
class NotifyRecipientsJob < ApplicationJob
  def perform(card)
    card.notify_recipients
  end
end

Constant Summary collapse

MSG =
'Job `perform` has too many statements (%<count>d/%<max>d). Move logic to a model method.'

Instance Method Summary collapse

Instance Method Details

#on_def(node) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/rubocop/cop/guardrails/shallow_job.rb', line 36

def on_def(node)
  if node.method?(:perform)
    count = statement_count(node)
    if count > max_statements
      add_offense(node.loc.name, message: format(MSG, count: count, max: max_statements))
    end
  end
end