Class: RuboCop::Cop::DevDoc::Style::AvoidHeadResponse

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/dev_doc/style/avoid_head_response.rb

Overview

Avoid ‘head()` responses in controllers.

## Rationale ‘head()` returns an empty body with no useful information for the client. Its presence is usually a sign that error handling should be delegated to Rails exceptions (e.g. `ActiveRecord::RecordNotFound`) or model validations instead.

If you find yourself reaching for ‘head()`, consider whether a well-known Rails exception or a model validation can handle the case more cleanly:

❌ Manually returns 404 with no body
def show
  @user = User.find_by(id: params[:id])
  head(:not_found) unless @user
end

✔️ Let Rails raise RecordNotFound — it renders the standard 404
def show
  @user = User.find(params[:id])
end

NOTE: The cop flags every bare ‘head(…)` call. Some legitimate uses (e.g. `head :no_content` for a successful DELETE, or simple webhook acknowledgements) still get flagged — disable per-line in those cases.

Examples:

# bad
def glib_load_resource
  @user = User.find_by(id: params[:id])
  head(:not_found) unless @user
end

# good
def glib_load_resource
  @user = User.find(params[:id])
end

Constant Summary collapse

MSG =
'Avoid `head()`. Delegate error handling to Rails exceptions ' \
'(e.g. use `find` instead of `find_by` + `head(:not_found)`) or model validations.'.freeze
RESTRICT_ON_SEND =
%i[head].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



48
49
50
51
52
# File 'lib/rubocop/cop/dev_doc/style/avoid_head_response.rb', line 48

def on_send(node)
  return unless node.receiver.nil?

  add_offense(node.loc.selector)
end