Class: RuboCop::Cop::Rails::HttpStatus

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ConfigurableEnforcedStyle
Defined in:
lib/rubocop/cop/rails/http_status.rb

Overview

Enforces use of symbolic or numeric value to define HTTP status.

Examples:

EnforcedStyle: symbolic (default)

# bad
render :foo, status: 200
render :foo, status: '200'
render json: { foo: 'bar' }, status: 200
render plain: 'foo/bar', status: 304
redirect_to root_url, status: 301
head 200

# good
render :foo, status: :ok
render json: { foo: 'bar' }, status: :ok
render plain: 'foo/bar', status: :not_modified
redirect_to root_url, status: :moved_permanently
head :ok

EnforcedStyle: numeric

# bad
render :foo, status: :ok
render json: { foo: 'bar' }, status: :not_found
render plain: 'foo/bar', status: :not_modified
redirect_to root_url, status: :moved_permanently
head :ok

# good
render :foo, status: 200
render json: { foo: 'bar' }, status: 404
render plain: 'foo/bar', status: 304
redirect_to root_url, status: 301
head 200

Defined Under Namespace

Classes: NumericStyleChecker, SymbolicStyleChecker

Constant Summary collapse

RESTRICT_ON_SEND =
%i[render redirect_to head].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rubocop/cop/rails/http_status.rb', line 57

def on_send(node)
  http_status(node) do |hash_node_or_status_code|
    status = if hash_node_or_status_code.hash_type?
               status_code(hash_node_or_status_code)
             else
               hash_node_or_status_code
             end
    return unless status

    checker = checker_class.new(status)
    return unless checker.offensive?

    add_offense(checker.node, message: checker.message) do |corrector|
      corrector.replace(checker.node, checker.preferred_style)
    end
  end
end