Skip to content

Commit

Permalink
Fix Style/EmptyCaseCondition's autocorrect.
Browse files Browse the repository at this point in the history
Avoids incorrect use of `comments_before_line`.
The autocorrection worked only for case statements that were root of the document and were not indented
Also fix `Style/SafeNavigation`'s auto-correction, typical off-by-one error without a spec
  • Loading branch information
marcandre authored and bbatsov committed Aug 10, 2020
1 parent 14a5c20 commit 28eabb7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 31 deletions.
17 changes: 8 additions & 9 deletions lib/rubocop/cop/style/empty_case_condition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def correct_case_when(corrector, case_node, when_nodes)

corrector.replace(case_range, 'if')

keep_first_when_comment(case_node, when_nodes.first, corrector)
keep_first_when_comment(case_range, corrector)

when_nodes[1..-1].each do |when_node|
corrector.replace(when_node.loc.keyword, 'elsif')
Expand All @@ -93,15 +93,14 @@ def correct_when_conditions(corrector, when_nodes)
end
end

def keep_first_when_comment(case_node, first_when_node, corrector)
comment = processed_source.comments_before_line(
first_when_node.loc.keyword.line
).map(&:text).join("\n")
def keep_first_when_comment(case_range, corrector)
indent = ' ' * case_range.column
comments = processed_source.each_comment_in_lines(
case_range.first_line...case_range.last_line
).map { |comment| "#{indent}#{comment.text}\n" }.join

line = range_by_whole_lines(case_node.source_range)

corrector.insert_before(line, "#{comment}\n") if !comment.empty? &&
!case_node.parent
line_beginning = case_range.adjust(begin_pos: -case_range.column)
corrector.insert_before(line_beginning, comments)
end
end
end
Expand Down
51 changes: 29 additions & 22 deletions spec/rubocop/cop/style/empty_case_condition_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,33 +49,40 @@
context 'with multiple when branches and an `else` with code comments' do
let(:source) do
<<~RUBY
case
^^^^ Do not use empty `case` condition, instead use an `if` expression.
# condition a
# This is a multi-line comment
when 1 == 2
foo
# condition b
when 1 == 1
bar
# condition c
else
baz
def example
# Comment before everything
case # first comment
^^^^ Do not use empty `case` condition, instead use an `if` expression.
# condition a
# This is a multi-line comment
when 1 == 2
foo
# condition b
when 1 == 1
bar
# condition c
else
baz
end
end
RUBY
end
let(:corrected_source) do
<<~RUBY
# condition a
# This is a multi-line comment
if 1 == 2
foo
# condition b
elsif 1 == 1
bar
# condition c
else
baz
def example
# Comment before everything
# first comment
# condition a
# This is a multi-line comment
if 1 == 2
foo
# condition b
elsif 1 == 1
bar
# condition c
else
baz
end
end
RUBY
end
Expand Down

0 comments on commit 28eabb7

Please sign in to comment.