Skip to content

Commit

Permalink
Merge pull request #11156 from gsamokovarov/operator-method-chaining-…
Browse files Browse the repository at this point in the history
…call

Fix `Style/OperatorMethodCall` autocorrection when operators are chained
  • Loading branch information
koic authored Nov 5, 2022
2 parents 0d6b0d1 + 5cd0a9e commit d16a1f0
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_styleoperatormethodcall.md
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit d16a1f0

Please sign in to comment.