Skip to content

Commit

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

This PR fixes an error for `Style/IfUnlessModifier` when
variable assignment is used in the branch body of if modifier.
  • Loading branch information
koic committed Apr 22, 2021
1 parent 93a2379 commit 707ac30
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_style_if_unless_modifier.md
@@ -0,0 +1 @@
* [#9729](https://github.com/rubocop/rubocop/issues/9729): Fix an error for `Style/IfUnlessModifier` when variable assignment is used in the branch body of if modifier. ([@koic][])
7 changes: 3 additions & 4 deletions lib/rubocop/cop/style/if_unless_modifier.rb
Expand Up @@ -67,15 +67,14 @@ def on_if(node)

def autocorrect(corrector, node)
replacement = if node.modifier_form?
indentation = ' ' * node.source_range.column
last_argument = node.if_branch.last_argument
last_argument = node.if_branch.last_argument if node.if_branch.send_type?

if last_argument.respond_to?(:heredoc?) && last_argument.heredoc?
heredoc = extract_heredoc_from(last_argument)
remove_heredoc(corrector, heredoc)
to_normal_form_with_heredoc(node, indentation, heredoc)
to_normal_form_with_heredoc(node, indent(node), heredoc)
else
to_normal_form(node, indentation)
to_normal_form(node, indent(node))
end
else
to_modifier_form(node)
Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cop/style/if_unless_modifier_spec.rb
Expand Up @@ -92,6 +92,21 @@ def f
end
end

context 'when variable assignment is used in the branch body of if modifier' do
it 'registers an offense' do
expect_offense(<<~RUBY)
variable = foooooooooooooooooooooooooooooooooooooooooooooooooooooooo if condition
^^ Modifier form of `if` makes the line too long.
RUBY

expect_correction(<<~RUBY)
if condition
variable = foooooooooooooooooooooooooooooooooooooooooooooooooooooooo
end
RUBY
end
end

describe 'IgnoreCopDirectives' do
let(:spaces) { ' ' * 57 }
let(:comment) { '# rubocop:disable Style/For' }
Expand Down

0 comments on commit 707ac30

Please sign in to comment.