diff --git a/CHANGELOG.md b/CHANGELOG.md index 71f1df859c1..a6f3641a224 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ * [#6902](https://github.com/rubocop-hq/rubocop/issues/6902): Fix a bug where `Naming/RescuedExceptionsVariableName` would handle an only first rescue for multiple rescue groups. ([@tatsuyafw][]) * [#6860](https://github.com/rubocop-hq/rubocop/issues/6860): Prevent auto-correct conflict of `Style/InverseMethods` and `Style/Not`. ([@hoshinotsuyoshi][]) * [#6935](https://github.com/rubocop-hq/rubocop/issues/6935): `Layout/AccessModifierIndentation` should ignore access modifiers that apply to specific methods. ([@deivid-rodriguez][]) +* [#6956](https://github.com/rubocop-hq/rubocop/issues/6956): Prevent auto-correct confliction of `Lint/Lambda` and `Lint/UnusedBlockArgument`. ([@koic][]) ### Changes diff --git a/lib/rubocop/cop/correctors/unused_arg_corrector.rb b/lib/rubocop/cop/correctors/unused_arg_corrector.rb index 04b6e210b8d..c3a3d0a916b 100644 --- a/lib/rubocop/cop/correctors/unused_arg_corrector.rb +++ b/lib/rubocop/cop/correctors/unused_arg_corrector.rb @@ -15,14 +15,26 @@ def correct(processed_source, node) @processed_source = processed_source if node.blockarg_type? + correct_for_blockarg_type(node) + else lambda do |corrector| - range = range_with_surrounding_space(range: node.source_range, - side: :left) - range = range_with_surrounding_comma(range, :left) - corrector.remove(range) + variable_name = if node.optarg_type? + node.node_parts[0] + else + # Extract only a var name without splat (`*`) + node.source.gsub(/\A\*+/, '') + end + corrector.replace(node.loc.name, "_#{variable_name}") end - else - ->(corrector) { corrector.insert_before(node.loc.name, '_') } + end + end + + def correct_for_blockarg_type(node) + lambda do |corrector| + range = range_with_surrounding_space(range: node.source_range, + side: :left) + range = range_with_surrounding_comma(range, :left) + corrector.remove(range) end end end diff --git a/spec/rubocop/cli/cli_autocorrect_spec.rb b/spec/rubocop/cli/cli_autocorrect_spec.rb index ed2ddaea344..efefb51c7b7 100644 --- a/spec/rubocop/cli/cli_autocorrect_spec.rb +++ b/spec/rubocop/cli/cli_autocorrect_spec.rb @@ -467,6 +467,25 @@ def verify_section expect(IO.read('example.rb')).to eq(corrected) end + it 'corrects `Lint/Lambda` and `Lint/UnusedBlockArgument` offenses' do + source = <<-'RUBY'.strip_indent + c = -> event do + puts 'Hello world' + end + RUBY + create_file('example.rb', source) + expect(cli.run([ + '--auto-correct', + '--only', 'Lint/Lambda,Lint/UnusedBlockArgument' + ])).to eq(0) + corrected = <<-'RUBY'.strip_indent + c = lambda do |_event| + puts 'Hello world' + end + RUBY + expect(IO.read('example.rb')).to eq(corrected) + end + describe 'caching' do let(:cache) do instance_double(RuboCop::ResultCache, 'valid?' => true,