Skip to content

Commit

Permalink
[Fix rubocop#9333] Fix an error for Style/IfInsideElse
Browse files Browse the repository at this point in the history
Fixes rubocop#9333.

This PR fixes an error for `Style/IfInsideElse`
when using a modifier `if` nested inside an `else` after `elsif`.
  • Loading branch information
koic committed Jan 5, 2021
1 parent 1d75a82 commit f7edb18
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_style_if_inside_else.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#9333](https://github.com/rubocop-hq/rubocop/issues/9333): Fix an error for `Style/IfInsideElse` when using a modifier `if` nested inside an `else` after `elsif`. ([@koic][])
11 changes: 8 additions & 3 deletions lib/rubocop/cop/style/if_inside_else.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,10 @@ def on_if(node)
def autocorrect(corrector, node)
if node.modifier_form?
correct_to_elsif_from_modifier_form(corrector, node)
end_range = node.parent.loc.end
else
correct_to_elsif_from_if_inside_else_form(corrector, node, node.condition)
end_range = node.loc.end
end
corrector.remove(range_by_whole_lines(end_range, include_final_newline: true))
corrector.remove(range_by_whole_lines(find_end_range(node), include_final_newline: true))
corrector.remove(
range_by_whole_lines(node.if_branch.source_range, include_final_newline: true)
)
Expand All @@ -110,6 +108,13 @@ def correct_to_elsif_from_if_inside_else_form(corrector, node, condition)
corrector.remove(condition)
end

def find_end_range(node)
end_range = node.loc.end
return end_range if end_range

find_end_range(node.parent)
end

def allow_if_modifier_in_else_branch?(else_branch)
allow_if_modifier? && else_branch&.modifier_form?
end
Expand Down
23 changes: 23 additions & 0 deletions spec/rubocop/cop/style/if_inside_else_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,29 @@
RUBY
end

it 'catches a modifier if nested inside an else after elsif' do
expect_offense(<<~RUBY)
if a
blah
elsif b
foo
else
bar if condition
^^ Convert `if` nested inside `else` to `elsif`.
end
RUBY

expect_correction(<<~RUBY)
if a
blah
elsif b
foo
elsif condition
bar
end
RUBY
end

context 'when AllowIfModifier is false' do
it 'catches a modifier if nested inside an else' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit f7edb18

Please sign in to comment.