Skip to content

Commit f89c1d3

Browse files
committed
Fix a false positive for Rails/TopLevelHashWithIndifferentAccess
This PR fixes a false positive for `Rails/TopLevelHashWithIndifferentAccess` when using `HashWithIndifferentAccess` under namespace module.
1 parent 32daa2f commit f89c1d3

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#772](https://github.com/rubocop/rubocop-rails/pull/772): Fix a false positive for `Rails/TopLevelHashWithIndifferentAccess` when using `HashWithIndifferentAccess` under namespace module. ([@koic][])

lib/rubocop/cop/rails/top_level_hash_with_indifferent_access.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ class TopLevelHashWithIndifferentAccess < Base
3131
# @param [RuboCop::AST::ConstNode] node
3232
def on_const(node)
3333
return unless top_level_hash_with_indifferent_access?(node)
34+
return if node.parent&.class_type? && node.parent.ancestors.any?(&:module_type?)
3435

3536
add_offense(node) do |corrector|
3637
autocorrect(corrector, node)

spec/rubocop/cop/rails/top_level_hash_with_indifferent_access_spec.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,19 @@
2727
end
2828
end
2929

30+
context 'with top-level `HashWithIndifferentAccess` without method call' do
31+
it 'registers and corrects an offense' do
32+
expect_offense(<<~RUBY)
33+
HashWithIndifferentAccess
34+
^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid top-level `HashWithIndifferentAccess`.
35+
RUBY
36+
37+
expect_correction(<<~RUBY)
38+
ActiveSupport::HashWithIndifferentAccess
39+
RUBY
40+
end
41+
end
42+
3043
context 'with ActiveSupport::HashWithIndifferentAccess' do
3144
it 'does not register an offense' do
3245
expect_no_offenses(<<~RUBY)
@@ -35,6 +48,17 @@
3548
end
3649
end
3750

51+
context 'with `HashWithIndifferentAccess` under the namespace' do
52+
it 'does not register an offense' do
53+
expect_no_offenses(<<~RUBY)
54+
module CoreExt
55+
class HashWithIndifferentAccess
56+
end
57+
end
58+
RUBY
59+
end
60+
end
61+
3862
context 'with ActiveSupport::HashWithIndifferentAccess on Rails 5.0', :rails50 do
3963
it 'does not register an offense' do
4064
expect_no_offenses(<<~RUBY)

0 commit comments

Comments
 (0)