From fc242945bae5c63cd512ff579d6bef81824858f2 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Thu, 16 Apr 2020 01:41:51 +0900 Subject: [PATCH] Fix a false positive for `Layout/SpaceAroundMethodCallOperator` This PR fixes the following false positive for `Layout/SpaceAroundMethodCallOperator` cop when there is a space between `.` operator and a comment. ```ruby foo. # comment bar.baz ``` ```console % rubocop --only Layout/SpaceAroundMethodCallOperator (snip) Inspecting 1 file C Offenses: example.rb:1:5: C: Layout/SpaceAroundMethodCallOperator: Avoid using spaces around a method call operator. foo. # comment ^ 1 file inspected, 1 offense detected ``` Also this PR does not add to the changelog entry because `Layout/SpaceAroundMethodCallOperator` cop has not been released yet. --- .../space_around_method_call_operator.rb | 6 +++-- .../space_around_method_call_operator_spec.rb | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/rubocop/cop/layout/space_around_method_call_operator.rb b/lib/rubocop/cop/layout/space_around_method_call_operator.rb index 78b9b473fac..160e28b1d3e 100644 --- a/lib/rubocop/cop/layout/space_around_method_call_operator.rb +++ b/lib/rubocop/cop/layout/space_around_method_call_operator.rb @@ -72,7 +72,7 @@ def check_and_add_offense(node, add_left_offense = true) left = previous_token(operator) right = next_token(operator) - if valid_right_token?(right, operator) + if !right.comment? && valid_right_token?(right, operator) no_space_offenses(node, operator, right, MSG) end return unless valid_left_token?(left, operator) @@ -121,7 +121,9 @@ def left_token_for_auto_correction(node, operator) def right_token_for_auto_correction(operator) right_token = next_token(operator) - return right_token if valid_right_token?(right_token, operator) + if !right_token.comment? && valid_right_token?(right_token, operator) + return right_token + end operator end diff --git a/spec/rubocop/cop/layout/space_around_method_call_operator_spec.rb b/spec/rubocop/cop/layout/space_around_method_call_operator_spec.rb index 970cc6b6961..e4e9e97880a 100644 --- a/spec/rubocop/cop/layout/space_around_method_call_operator_spec.rb +++ b/spec/rubocop/cop/layout/space_around_method_call_operator_spec.rb @@ -177,6 +177,28 @@ foo.bar.buzz RUBY end + + context 'when there is a space between `.` operator and a comment' do + it 'does not register an offense when there is not a space before `.`' do + expect_no_offenses(<<~RUBY) + foo. # comment + bar.baz + RUBY + end + + it 'registers an offense when there is a space before `.`' do + expect_offense(<<~RUBY) + foo . # comment + ^ Avoid using spaces around a method call operator. + bar.baz + RUBY + + expect_correction(<<~RUBY) + foo. # comment + bar.baz + RUBY + end + end end context 'safe navigation operator' do