Skip to content

Commit

Permalink
Merge pull request rubocop#8210 from fatkodima/fix-redundant_fetch_bl…
Browse files Browse the repository at this point in the history
…ock-for-rails-cache

Fix a false positive for `Style/RedundantFetchBlock` when using with `Rails.cache`
  • Loading branch information
koic committed Jun 26, 2020
2 parents 423323c + 85ea97d commit 8e365cf
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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][])
Expand Down
13 changes: 11 additions & 2 deletions lib/rubocop/cop/style/redundant_fetch_block.rb
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions spec/rubocop/cop/style/redundant_fetch_block_spec.rb
Expand Up @@ -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
Expand Down

0 comments on commit 8e365cf

Please sign in to comment.