From d03ef0c85217c92ef1a91c8492d0dbe6d963f7df Mon Sep 17 00:00:00 2001 From: Daniel Vandersluis Date: Thu, 5 Aug 2021 15:13:27 -0400 Subject: [PATCH] Update `Layout/SpaceBeforeComment` to handle heredocs. --- .../fix_update_layoutspacebeforecomment_to.md | 1 + lib/rubocop/cop/layout/space_before_comment.rb | 2 +- .../cop/layout/space_before_comment_spec.rb | 15 +++++++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_update_layoutspacebeforecomment_to.md diff --git a/changelog/fix_update_layoutspacebeforecomment_to.md b/changelog/fix_update_layoutspacebeforecomment_to.md new file mode 100644 index 00000000000..40920315793 --- /dev/null +++ b/changelog/fix_update_layoutspacebeforecomment_to.md @@ -0,0 +1 @@ +* [#9984](https://github.com/rubocop/rubocop/pull/9984): Fix false negatives involving heredocs for `Layout/SpaceBeforeComma`, `Layout/SpaceBeforeComment`, `Layout/SpaceBeforeSemicolon` and `Layout/SpaceInsideParens`. ([@dvandersluis][]) diff --git a/lib/rubocop/cop/layout/space_before_comment.rb b/lib/rubocop/cop/layout/space_before_comment.rb index 8dd442acde1..77d32ce2e6d 100644 --- a/lib/rubocop/cop/layout/space_before_comment.rb +++ b/lib/rubocop/cop/layout/space_before_comment.rb @@ -18,7 +18,7 @@ class SpaceBeforeComment < Base MSG = 'Put a space before an end-of-line comment.' def on_new_investigation - processed_source.tokens.each_cons(2) do |token1, token2| + processed_source.sorted_tokens.each_cons(2) do |token1, token2| next unless token2.comment? next unless token1.line == token2.line next unless token1.pos.end == token2.pos.begin diff --git a/spec/rubocop/cop/layout/space_before_comment_spec.rb b/spec/rubocop/cop/layout/space_before_comment_spec.rb index eb720045aa7..1b40c44ff0e 100644 --- a/spec/rubocop/cop/layout/space_before_comment_spec.rb +++ b/spec/rubocop/cop/layout/space_before_comment_spec.rb @@ -27,4 +27,19 @@ =end RUBY end + + it 'registers an offense and corrects after a heredoc' do + expect_offense(<<~RUBY) + <<~STR# my string + ^^^^^^^^^^^ Put a space before an end-of-line comment. + text + STR + RUBY + + expect_correction(<<~RUBY) + <<~STR # my string + text + STR + RUBY + end end