Skip to content

Commit

Permalink
[Fix rubocop#12693] Fix an incorrect autocorrect for Style/ObjectThen
Browse files Browse the repository at this point in the history
Fixes rubocop#12693.

This PR fixes an incorrect autocorrect for `Style/ObjectThen`
when using `yield_self` without receiver.
  • Loading branch information
koic committed Feb 16, 2024
1 parent b766bfa commit 3f1a637
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
1 change: 1 addition & 0 deletions changelog/fix_an_incorrect_for_style_object_then.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12693](https://github.com/rubocop/rubocop/issues/12693): Fix an incorrect autocorrect for `Style/ObjectThen` when using `yield_self` without receiver. ([@koic][])
12 changes: 7 additions & 5 deletions lib/rubocop/cop/style/object_then.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,22 @@ def on_send(node)
private

def check_method_node(node)
return unless preferred_method(node)
return if preferred_method?(node)

message = message(node)
add_offense(node.loc.selector, message: message) do |corrector|
corrector.replace(node.loc.selector, style.to_s)
prefer = style == :then && node.receiver.nil? ? 'self.then' : style

corrector.replace(node.loc.selector, prefer)
end
end

def preferred_method(node)
def preferred_method?(node)
case style
when :then
node.method?(:yield_self)
when :yield_self
node.method?(:then)
when :yield_self
node.method?(:yield_self)
else
false
end
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/style/object_then_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@
obj.then { _1.test }
RUBY
end

it 'registers an offense for `yield_self` without receiver' do
expect_offense(<<~RUBY)
yield_self { |obj| obj.test }
^^^^^^^^^^ Prefer `then` over `yield_self`.
RUBY

expect_correction(<<~RUBY)
self.then { |obj| obj.test }
RUBY
end
end

it 'registers an offense for yield_self with proc param' do
Expand Down

0 comments on commit 3f1a637

Please sign in to comment.