diff --git a/changelog/fix_an_error_for_style_if_unless_modifier.md b/changelog/fix_an_error_for_style_if_unless_modifier.md new file mode 100644 index 00000000000..b9bded086a4 --- /dev/null +++ b/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][]) diff --git a/lib/rubocop/cop/style/if_unless_modifier.rb b/lib/rubocop/cop/style/if_unless_modifier.rb index df77e7079d3..5b7594a3757 100644 --- a/lib/rubocop/cop/style/if_unless_modifier.rb +++ b/lib/rubocop/cop/style/if_unless_modifier.rb @@ -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) diff --git a/spec/rubocop/cop/style/if_unless_modifier_spec.rb b/spec/rubocop/cop/style/if_unless_modifier_spec.rb index d19da999e71..5f7ed6cff12 100644 --- a/spec/rubocop/cop/style/if_unless_modifier_spec.rb +++ b/spec/rubocop/cop/style/if_unless_modifier_spec.rb @@ -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' }