Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Style/OperatorMethodCall autocorrection when operators are chained #11156

Merged
merged 1 commit into from Nov 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/fix_styleoperatormethodcall.md
@@ -0,0 +1 @@
* [#11156](https://github.com/rubocop/rubocop/pull/11156): Fix `Style/OperatorMethodCall` autocorrection when operators are chained. ([@gsamokovarov][])
13 changes: 13 additions & 0 deletions lib/rubocop/cop/style/operator_method_call.rb
Expand Up @@ -31,9 +31,22 @@ def on_send(node)
return if rhs.nil? || rhs.children.first

add_offense(dot) do |corrector|
wrap_in_parentheses_if_chained(corrector, node)
corrector.replace(dot, ' ')
end
end

private

def wrap_in_parentheses_if_chained(corrector, node)
return unless node.parent&.call_type?

operator = node.loc.selector

ParenthesesCorrector.correct(corrector, node)
corrector.insert_after(operator, ' ')
corrector.wrap(node, '(', ')')
end
end
end
end
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/style/operator_method_call_spec.rb
Expand Up @@ -30,6 +30,17 @@
foo #{operator_method}(bar)
RUBY
end

it "registers an offense when chaining `foo.bar.#{operator_method}(baz).round(2)`" do
expect_offense(<<~RUBY, operator_method: operator_method)
foo.bar.#{operator_method}(baz).quux(2)
^ Redundant dot detected.
RUBY

expect_correction(<<~RUBY)
(foo.bar #{operator_method} baz).quux(2)
RUBY
end
end

it 'does not register an offense when using `foo.+@bar.to_s`' do
Expand Down