From b72c896cd6f11355b6d74005cc55f3b76686fc26 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Thu, 2 Sep 2021 10:46:55 +0900 Subject: [PATCH] [Fix #532] Fix a false positive for `Rails/HttpPositionalArguments` Fixes #532. This PR fixes a false positive for `Rails/HttpPositionalArguments` when defining `get` in `Rails.application.routes.draw` block. --- CHANGELOG.md | 1 + .../cop/rails/http_positional_arguments.rb | 7 +++++++ .../cop/rails/http_positional_arguments_spec.rb | 16 ++++++++++++++++ 3 files changed, 24 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5611f5626e..9d3c37b5f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ ### Bug fixes * [#528](https://github.com/rubocop/rubocop-rails/issues/528): Fix a false positive for `Rails/HasManyOrHasOneDependent` when specifying `:dependent` strategy with double splat. ([@koic][]) +* [#532](https://github.com/rubocop/rubocop-rails/issues/532): Fix a false positive for `Rails/HttpPositionalArguments` when defining `get` in `Rails.application.routes.draw` block. ([@koic][]) ## Changes diff --git a/lib/rubocop/cop/rails/http_positional_arguments.rb b/lib/rubocop/cop/rails/http_positional_arguments.rb index 07f437c7db..32536f4eda 100644 --- a/lib/rubocop/cop/rails/http_positional_arguments.rb +++ b/lib/rubocop/cop/rails/http_positional_arguments.rb @@ -27,6 +27,7 @@ class HttpPositionalArguments < Base KEYWORD_ARGS = %i[ method params session body flash xhr as headers env to ].freeze + ROUTING_METHODS = %i[draw routes].freeze RESTRICT_ON_SEND = %i[get post put patch delete head].freeze minimum_target_rails_version 5.0 @@ -40,6 +41,8 @@ class HttpPositionalArguments < Base PATTERN def on_send(node) + return if in_routing_block?(node) + http_request?(node) do |data| return unless needs_conversion?(data) @@ -63,6 +66,10 @@ def on_send(node) private + def in_routing_block?(node) + !!node.each_ancestor(:block).detect { |block| ROUTING_METHODS.include?(block.send_node.method_name) } + end + def needs_conversion?(data) return true unless data.hash_type? return false if kwsplat_hash?(data) diff --git a/spec/rubocop/cop/rails/http_positional_arguments_spec.rb b/spec/rubocop/cop/rails/http_positional_arguments_spec.rb index 3564069eac..caa3376041 100644 --- a/spec/rubocop/cop/rails/http_positional_arguments_spec.rb +++ b/spec/rubocop/cop/rails/http_positional_arguments_spec.rb @@ -415,5 +415,21 @@ RUBY end end + + it 'does not register an offense when defining `get` in `routes` block' do + expect_no_offenses(<<~RUBY) + routes do + get :list, on: :collection + end + RUBY + end + + it 'does not register an offense when defining `get` in `routes.draw` block' do + expect_no_offenses(<<~RUBY) + Rails.application.routes.draw do + get :list, on: :collection + end + RUBY + end end end