Skip to content

Commit

Permalink
[Fix #11120] Fix an incorrect autocorrect for `Lint/RedundantRequireS…
Browse files Browse the repository at this point in the history
…tatement`

Fixes #11120.

This PR fixes an incorrect autocorrect for `Lint/RedundantRequireStatement`
when using redundant `require` with modifier form.

For example, in essential it is unknown how many times `do_something` will be
executed when `require 'enumerator' while do_something`.
So it does not autocorrects when modifier form is used to avoid side effects.
  • Loading branch information
koic authored and bbatsov committed Oct 30, 2022
1 parent a469efb commit 06cacae
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
@@ -0,0 +1 @@
* [#11120](https://github.com/rubocop/rubocop/issues/11120): Fix an incorrect autocorrect for `Lint/RedundantRequireStatement` when using redundant `require` with modifier form. ([@koic][])
8 changes: 7 additions & 1 deletion lib/rubocop/cop/lint/redundant_require_statement.rb
Expand Up @@ -49,7 +49,13 @@ def on_send(node)
return unless redundant_require_statement?(node)

add_offense(node) do |corrector|
range = range_with_surrounding_space(node.loc.expression, side: :right)
if node.parent.respond_to?(:modifier_form?) && node.parent.modifier_form?
corrector.insert_after(node.parent, "\nend")

range = range_with_surrounding_space(node.loc.expression, side: :right)
else
range = range_by_whole_lines(node.source_range, include_final_newline: true)
end

corrector.remove(range)
end
Expand Down
30 changes: 30 additions & 0 deletions spec/rubocop/cop/lint/redundant_require_statement_spec.rb
Expand Up @@ -13,6 +13,36 @@
RUBY
end

it 'registers an offense when using requiring `enumerator` with modifier form' do
expect_offense(<<~RUBY)
require 'enumerator' if condition
^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement.
require 'uri'
RUBY

expect_correction(<<~RUBY)
if condition
end
require 'uri'
RUBY
end

it 'registers an offense when using requiring `enumerator` in condition' do
expect_offense(<<~RUBY)
if condition
require 'enumerator'
^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement.
end
require 'uri'
RUBY

expect_correction(<<~RUBY)
if condition
end
require 'uri'
RUBY
end

context 'target ruby version <= 2.0', :ruby20 do
it 'does not register an offense when using requiring `thread`' do
expect_no_offenses(<<~RUBY)
Expand Down

0 comments on commit 06cacae

Please sign in to comment.