Skip to content

Commit de56890

Browse files
committed
Fix blank line indentation for unless statements
Previously, the cop was only tracking indentation deltas for 'if' statements but not 'unless' statements, even though both are parsed as :if nodes. This caused blank lines inside unless blocks to be incorrectly flagged or 'corrected' to the wrong indentation level. The fix includes 'unless' statements in the condition that creates indentation deltas, ensuring blank lines inside unless blocks are properly indented to match their context. Fixes issue where blank lines inside nested unless blocks were incorrectly rewritten from two tabs to one tab.
1 parent f998562 commit de56890

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

lib/rubocop/socketry/layout/consistent_blank_line_indentation.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def walk_ast_for_indentation(node, deltas, parent = nil)
125125
end
126126
when :if
127127
# We don't want to add deltas for elsif, because it's handled by the if node:
128-
if node.keyword == "if"
128+
if node.keyword == "if" || node.keyword == "unless"
129129
if location = node.location
130130
deltas[location.line] += 1
131131
deltas[location.last_line] -= 1

test/rubocop/socketry/layout/consistent_blank_line_indentation.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -683,4 +683,31 @@ def foo
683683
expect(offenses).to be(:empty?)
684684
end
685685
end
686+
687+
# This test case specifically demonstrates the issue described by the user
688+
with "a blank line inside nested unless block" do
689+
let(:source) {"def hello(foo)\n\tunless foo\n\t\tx = 10\n\t\t\n\t\ty = 20\n\tend\nend\n"}
690+
691+
it "should properly indent blank line with two tabs inside nested unless block" do
692+
processed_source = RuboCop::ProcessedSource.new(source, RUBY_VERSION.to_f)
693+
investigator = RuboCop::Cop::Commissioner.new([cop], [], raise_error: true)
694+
report = investigator.investigate(processed_source)
695+
offenses = report.offenses
696+
expect(offenses).to be(:empty?)
697+
end
698+
end
699+
700+
# This test case shows the current incorrect behavior
701+
with "a blank line inside nested unless block with incorrect indentation" do
702+
let(:source) {"def hello(foo)\n\tunless foo\n\t\tx = 10\n\t\n\t\ty = 20\n\tend\nend\n"}
703+
704+
it "should register an offense when blank line has only one tab instead of two" do
705+
processed_source = RuboCop::ProcessedSource.new(source, RUBY_VERSION.to_f)
706+
investigator = RuboCop::Cop::Commissioner.new([cop], [], raise_error: true)
707+
report = investigator.investigate(processed_source)
708+
offenses = report.offenses
709+
expect(offenses).not.to be(:empty?)
710+
expect(offenses.first.message).to be(:include?, message)
711+
end
712+
end
686713
end

0 commit comments

Comments
 (0)