From 1597468eb21e779757495a0b540b6435d3484423 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sun, 21 Aug 2022 15:01:44 +0900 Subject: [PATCH] [Fix #10939] Fix an error for `Style/Next` Fixes #10939. This PR fixes an error for `Style/Next` when line break before condition. The removed indentation logic can be delegated to `Layout/IndentationConsistency`. --- changelog/fix_an_error_for_style_next.md | 1 + lib/rubocop/cop/style/next.rb | 6 +----- spec/rubocop/cop/style/next_spec.rb | 21 +++++++++++++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) create mode 100644 changelog/fix_an_error_for_style_next.md diff --git a/changelog/fix_an_error_for_style_next.md b/changelog/fix_an_error_for_style_next.md new file mode 100644 index 00000000000..fbf419b47e6 --- /dev/null +++ b/changelog/fix_an_error_for_style_next.md @@ -0,0 +1 @@ +* [#10939](https://github.com/rubocop/rubocop/issues/10939): Fix an error for `Style/Next` when line break before condition. ([@koic][]) diff --git a/lib/rubocop/cop/style/next.rb b/lib/rubocop/cop/style/next.rb index e17db2cb62b..5f310abf720 100644 --- a/lib/rubocop/cop/style/next.rb +++ b/lib/rubocop/cop/style/next.rb @@ -225,11 +225,7 @@ def reindent_line(corrector, lineno, delta, buffer) adjustment = delta + @reindented_lines[lineno] @reindented_lines[lineno] = adjustment - if adjustment.positive? - corrector.remove_leading(buffer.line_range(lineno), adjustment) - elsif adjustment.negative? - corrector.insert_before(buffer.line_range(lineno), ' ' * -adjustment) - end + corrector.remove_leading(buffer.line_range(lineno), adjustment) if adjustment.positive? end end end diff --git a/spec/rubocop/cop/style/next_spec.rb b/spec/rubocop/cop/style/next_spec.rb index e1f214ea82a..c21774e903e 100644 --- a/spec/rubocop/cop/style/next_spec.rb +++ b/spec/rubocop/cop/style/next_spec.rb @@ -315,6 +315,27 @@ RUBY end + it 'registers an offense when line break before condition' do + expect_offense(<<~RUBY) + array.each do |item| + if + ^^ Use `next` to skip iteration. + condition + next if item.zero? + do_something + end + end + RUBY + + expect_correction(<<~RUBY) + array.each do |item| + next unless condition + next if item.zero? + do_something + end + RUBY + end + it 'allows loops with conditional break' do expect_no_offenses(<<~RUBY) loop do