Class: EagerEye::Detectors::MissingCounterCache

Inherits:
Base
  • Object
show all
Defined in:
lib/eager_eye/detectors/missing_counter_cache.rb

Constant Summary collapse

COUNT_METHODS =
%i[count size length].freeze
PLURAL_ASSOCIATIONS =
%w[
  posts comments tags categories articles users members items orders products tasks projects
  images attachments documents files messages notifications reviews ratings followers followings
  likes favorites bookmarks votes children replies responses answers questions
].freeze
ITERATION_METHODS =
%i[each map collect select reject find_all filter filter_map flat_map
each_with_index each_with_object reduce inject sum].freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

default_severity

Class Method Details

.detector_nameObject



15
16
17
# File 'lib/eager_eye/detectors/missing_counter_cache.rb', line 15

def self.detector_name
  :missing_counter_cache
end

Instance Method Details

#detect(ast, file_path) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/eager_eye/detectors/missing_counter_cache.rb', line 19

def detect(ast, file_path)
  return [] unless ast

  issues = []

  traverse_ast(ast) do |node|
    next unless count_on_association?(node)
    next unless inside_iteration?(node)

    association_name = extract_association_name(node)
    next unless association_name

    issues << create_issue(
      file_path: file_path,
      line_number: node.loc.line,
      message: "`.#{node.children[1]}` called on `#{association_name}` inside iteration may cause N+1 queries",
      suggestion: "Consider adding `counter_cache: true` to the belongs_to association"
    )
  end

  issues
end