Skip to content

Commit

Permalink
[Fix #8990] Make Style/HashEachMethods aware of Thread.current
Browse files Browse the repository at this point in the history
Fixes #8990.

This PR makes `Style/HashEachMethods` aware of built-in `Thread.current`.
And `Thread.current` is set to `AllowedReceivers` by default that can be
specified for method calls.
  • Loading branch information
koic authored and bbatsov committed Jan 9, 2023
1 parent de30af8 commit 1e5f19a
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#8990](https://github.com/rubocop/rubocop/issues/8990): Make `Style/HashEachMethods` aware of built-in `Thread.current`. ([@koic][])
3 changes: 2 additions & 1 deletion config/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3858,7 +3858,8 @@ Style/HashEachMethods:
Safe: false
VersionAdded: '0.80'
VersionChanged: '1.16'
AllowedReceivers: []
AllowedReceivers:
- Thread.current

Style/HashExcept:
Description: >-
Expand Down
14 changes: 13 additions & 1 deletion lib/rubocop/cop/style/hash_each_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,23 @@ def kv_range(outer_node)
end

def allowed_receiver?(receiver)
receiver_name = receiver.send_type? ? receiver.method_name.to_s : receiver.source
receiver_name = receiver_name(receiver)

allowed_receivers.include?(receiver_name)
end

def receiver_name(receiver)
if receiver.send_type?
if receiver.receiver
"#{receiver_name(receiver.receiver)}.#{receiver.method_name}"
else
receiver.method_name.to_s
end
else
receiver.source
end
end

def allowed_receivers
cop_config.fetch('AllowedReceivers', [])
end
Expand Down
10 changes: 10 additions & 0 deletions spec/rubocop/cop/style/hash_each_methods_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -186,5 +186,15 @@
RUBY
end
end

context "when `AllowedReceivers: ['Thread.current']`" do
let(:cop_config) { { 'AllowedReceivers' => ['Thread.current'] } }

it 'does not register an offense when receiver is `Thread.current` method' do
expect_no_offenses(<<~RUBY)
Thread.current.keys.each { |k| p k }
RUBY
end
end
end
end

0 comments on commit 1e5f19a

Please sign in to comment.