Class: RuboCop::Cop::ScopeHunter::UseExistingScope

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/scope_hunter/use_existing_scope.rb

Constant Summary collapse

MSG =
'Query matches `%<model>s.%<scope>s`. Use the scope instead.'

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.project_indexObject (readonly)

Returns the value of attribute project_index.



22
23
24
# File 'lib/rubocop/cop/scope_hunter/use_existing_scope.rb', line 22

def project_index
  @project_index
end

Class Method Details

.ensure_project_index!Object



30
31
32
# File 'lib/rubocop/cop/scope_hunter/use_existing_scope.rb', line 30

def ensure_project_index!
  @project_index ||= ::ScopeHunter::ScopeIndex.new
end

.mark_model_files_scanned!Object



38
39
40
# File 'lib/rubocop/cop/scope_hunter/use_existing_scope.rb', line 38

def mark_model_files_scanned!
  @model_files_scanned = true
end

.model_files_scanned?Boolean

Returns:



34
35
36
# File 'lib/rubocop/cop/scope_hunter/use_existing_scope.rb', line 34

def model_files_scanned?
  @model_files_scanned
end

.reset_project_index!Object

Resets cross-file state. Call before each RSpec example to prevent pollution.



25
26
27
28
# File 'lib/rubocop/cop/scope_hunter/use_existing_scope.rb', line 25

def reset_project_index!
  @project_index = nil
  @model_files_scanned = false
end

Instance Method Details

#on_new_investigationObject



43
44
45
46
47
48
49
50
51
52
# File 'lib/rubocop/cop/scope_hunter/use_existing_scope.rb', line 43

def on_new_investigation
  self.class.ensure_project_index!

  unless self.class.model_files_scanned?
    self.class.mark_model_files_scanned!
    scan_model_files
  end

  index_scopes(processed_source.ast)
end

#on_send(node) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rubocop/cop/scope_hunter/use_existing_scope.rb', line 54

def on_send(node)
  chain = ::ScopeHunter::ASTUtils.relation_chain(node)
  return unless chain
  return if dynamic_where_values?(chain)

  model_name = chain.first[:recv]
  return if ignored_model?(model_name)

  sig = ::ScopeHunter::Canonicalizer.signature(chain)
  match = self.class.project_index&.find(sig)
  return unless match

  add_offense(node, message: format(MSG, model: match.model, scope: match.name)) do |corrector|
    replacement = replacement_for(node, match)
    corrector.replace(node.loc.expression, replacement) if replacement
  end
end