Class: EagerEye::Detectors::MissingCounterCache

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

Constant Summary collapse

COUNT_METHODS =

Methods that trigger COUNT queries

%i[count size length].freeze
PLURAL_ASSOCIATIONS =

Common has_many association names (plural)

%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 =

Iteration methods that indicate a loop context

%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



23
24
25
# File 'lib/eager_eye/detectors/missing_counter_cache.rb', line 23

def self.detector_name
  :missing_counter_cache
end

Instance Method Details

#detect(ast, file_path) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/eager_eye/detectors/missing_counter_cache.rb', line 27

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