diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d62509..bd8651d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ # main +* Added cop `Performance/Snif` ([#31](https://github.com/petalmd/rubocop-petal/pull/31)) * Updated gemspec file. ([#30](https://github.com/petalmd/rubocop-petal/pull/30)) * Added cop `RSpec/JsonParseResponseBody and RSpec/JsonResponse` ([#27](https://github.com/petalmd/rubocop-petal/pull/27)) diff --git a/config/default.yml b/config/default.yml index 1fc47ce..b0b8833 100644 --- a/config/default.yml +++ b/config/default.yml @@ -91,3 +91,7 @@ RSpec/JsonResponse: SafeAutoCorrect: true Include: - spec/**/* + +Performance/Snif: + Description: 'Prevent snif in favor of detect' + Enabled: true diff --git a/lib/rubocop/cop/performance/snif.rb b/lib/rubocop/cop/performance/snif.rb new file mode 100644 index 0000000..fc4368e --- /dev/null +++ b/lib/rubocop/cop/performance/snif.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + module Performance + # Prevent using `snif`. + # Consider using `detect`. + # + # @example + # # bad + # period.equity_packs.snif(:code, 'ONCALL') + # + # # good + # period.equity_packs.detect { |equity_pack| equity_pack.code == 'ONCALL' } + class Snif < Base + MSG = 'Use `detect` instead.' + + def_node_matcher :snif?, <<~PATTERN + (send _ :snif _ _) + PATTERN + + def on_send(node) + return unless snif?(node) + + add_offense(node) + end + end + end + end +end diff --git a/spec/rubocop/cop/performance/snif_spec.rb b/spec/rubocop/cop/performance/snif_spec.rb new file mode 100644 index 0000000..ada70bc --- /dev/null +++ b/spec/rubocop/cop/performance/snif_spec.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +RSpec.describe RuboCop::Cop::Performance::Snif, :config do + it 'registers an offense when using `snif`', :aggregate_failures do + expect_offense(<<~RUBY) + test.snif(:attribute, value) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `detect` instead. + RUBY + + expect_offense(<<~RUBY) + test.snif(attribute, value) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `detect` instead. + RUBY + end +end