diff --git a/CHANGELOG.md b/CHANGELOG.md index b57bdc09f09..e0debfe3ed8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ ### Bug fixes +* [#8196](https://github.com/rubocop-hq/rubocop/issues/8196): Fix a false positive for `Style/RedundantFetchBlock` when using with `Rails.cache`. ([@fatkodima][]) * [#8195](https://github.com/rubocop-hq/rubocop/issues/8195): Fix an error for `Style/RedundantFetchBlock` when using `#fetch` with empty block. ([@koic][]) * [#8193](https://github.com/rubocop-hq/rubocop/issues/8193): Fix a false positive for `Style/RedundantRegexpCharacterClass` when using `[\b]`. ([@owst][]) * [#8205](https://github.com/rubocop-hq/rubocop/issues/8205): Fix a false positive for `Style/RedundantRegexpCharacterClass` when using a leading escaped `]`. ([@owst][]) diff --git a/lib/rubocop/cop/style/redundant_fetch_block.rb b/lib/rubocop/cop/style/redundant_fetch_block.rb index 519157592d8..9fef8f5073e 100644 --- a/lib/rubocop/cop/style/redundant_fetch_block.rb +++ b/lib/rubocop/cop/style/redundant_fetch_block.rb @@ -46,8 +46,7 @@ class RedundantFetchBlock < Cop def on_block(node) redundant_fetch_block_candidate?(node) do |send, body| - return if body&.const_type? && !check_for_constant? - return if body&.str_type? && !check_for_string? + return if should_not_check?(send, body) range = fetch_range(send, node) good = build_good_method(send, body) @@ -82,6 +81,16 @@ def const_type?(node) node&.const_type? end + def should_not_check?(send, body) + (body&.const_type? && !check_for_constant?) || + (body&.str_type? && !check_for_string?) || + rails_cache?(send.receiver) + end + + def_node_matcher :rails_cache?, <<~PATTERN + (send (const _ :Rails) :cache) + PATTERN + def fetch_range(send, node) range_between(send.loc.selector.begin_pos, node.loc.end.end_pos) end diff --git a/spec/rubocop/cop/style/redundant_fetch_block_spec.rb b/spec/rubocop/cop/style/redundant_fetch_block_spec.rb index 3e5426f84cb..5f7343caa57 100644 --- a/spec/rubocop/cop/style/redundant_fetch_block_spec.rb +++ b/spec/rubocop/cop/style/redundant_fetch_block_spec.rb @@ -123,6 +123,12 @@ inspect_source('hash.fetch(:key) { |k| "missing-#{k}" }') expect(cop.offenses.size).to eq(0) end + + it 'does not register an offense when using `#fetch` with `Rails.cache`' do + expect_no_offenses(<<~RUBY) + Rails.cache.fetch(:key) { :value } + RUBY + end end context 'with SafeForConstants: false' do