Skip to content

Commit

Permalink
Merge pull request #1101 from koic/make_rails_http_status_aware_of_st…
Browse files Browse the repository at this point in the history
…ring_number_status

[Fix #1080] Make `Rails/HttpStatus` aware of string number status
  • Loading branch information
koic authored Sep 5, 2023
2 parents 8cfb90f + 411d119 commit baf39e6
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1080](https://github.com/rubocop/rubocop-rails/issues/1080): Make `Rails/HttpStatus` aware of string number status. ([@r7kamura][])
5 changes: 3 additions & 2 deletions lib/rubocop/cop/rails/http_status.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ module Rails
# @example 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
Expand Down Expand Up @@ -50,7 +51,7 @@ class HttpStatus < Base
PATTERN

def_node_matcher :status_code, <<~PATTERN
(hash <(pair (sym :status) ${int sym}) ...>)
(hash <(pair (sym :status) ${int sym str}) ...>)
PATTERN

def on_send(node)
Expand Down Expand Up @@ -108,7 +109,7 @@ def preferred_style
private

def symbol
::Rack::Utils::SYMBOL_TO_STATUS_CODE.key(number)
::Rack::Utils::SYMBOL_TO_STATUS_CODE.key(number.to_i)
end

def number
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/http_status_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,17 @@
RUBY
end

it 'registers an offense and corrects using numeric string value' do
expect_offense(<<~RUBY)
render :foo, status: '200'
^^^^^ Prefer `:ok` over `200` to define HTTP status code.
RUBY

expect_correction(<<~RUBY)
render :foo, status: :ok
RUBY
end

it 'does not register an offense when using symbolic value' do
expect_no_offenses(<<~RUBY)
render :foo, status: :ok
Expand Down

0 comments on commit baf39e6

Please sign in to comment.