diff --git a/changelog/change_make_rails_http_status_aware_of_string_number_status.md b/changelog/change_make_rails_http_status_aware_of_string_number_status.md new file mode 100644 index 0000000000..b05443a29d --- /dev/null +++ b/changelog/change_make_rails_http_status_aware_of_string_number_status.md @@ -0,0 +1 @@ +* [#1080](https://github.com/rubocop/rubocop-rails/issues/1080): Make `Rails/HttpStatus` aware of string number status. ([@r7kamura][]) diff --git a/lib/rubocop/cop/rails/http_status.rb b/lib/rubocop/cop/rails/http_status.rb index 63c91823b9..3401d6e5d0 100644 --- a/lib/rubocop/cop/rails/http_status.rb +++ b/lib/rubocop/cop/rails/http_status.rb @@ -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 @@ -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) @@ -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 diff --git a/spec/rubocop/cop/rails/http_status_spec.rb b/spec/rubocop/cop/rails/http_status_spec.rb index f7a6874113..093293cb62 100644 --- a/spec/rubocop/cop/rails/http_status_spec.rb +++ b/spec/rubocop/cop/rails/http_status_spec.rb @@ -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