Skip to content

Rubocop Rails/FindBy is not enforced

In light with the great MR series done by @arturoherrero (!27914 (merged), !27618 (merged)), we have noticed that a particular rule Rails/FindBy is not enforced across our backend code. Based on the doc (https://docs.rubocop.org/projects/rails/en/stable/cops_rails/#railsfindby), it seems like we need to override the Include attribute as the default value app/models/**/*.rb does not cover all.

bundle exec rubocop --show-cops Rails/FindBy
# Supports --auto-correct
Rails/FindBy:
  Description: Prefer find_by over where.first.
  StyleGuide: https://rails.rubystyle.guide#find_by
  Enabled: true
  VersionAdded: '0.30'
  Include:
  - app/models/**/*.rb

Perhaps we can extend this Include attribute on gitlab-styles gem.

diff --git .rubocop.yml .rubocop.yml
index a05fffe8740..39d294235df 100644
--- .rubocop.yml
+++ .rubocop.yml
@@ -161,6 +161,14 @@ Rails/ApplicationRecord:
     - ee/db/**/*.rb
     - ee/spec/**/*.rb
 
+Rails/FindBy:
+  Enabled: true
+  Include:
+    - app/**/*.rb
+    - ee/app/**/*.rb
+    - lib/**/*.rb
+    - ee/lib/**/*.rb
+
$ bundle exec rubocop --only Rails/FindBy app/finders/ --parallel
Warning: unrecognized cop Gitlab/DuplicateSpecLocation found in .rubocop.yml
Inspecting 79 files
..............................................C................................

Offenses:

app/finders/keys_finder.rb:49:10: C: Rails/FindBy: Use find_by instead of where.first.
    keys.where(fingerprint_query).first # rubocop: disable CodeReuse/ActiveRecord
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

79 files inspected, 1 offense detected
Edited by Tan Le