Class: Reek::SmellDetectors::InstanceVariableAssumption

Inherits:
BaseDetector
  • Object
show all
Defined in:
lib/reek/smell_detectors/instance_variable_assumption.rb

Overview

The InstanceVariableAssumption class is responsible for detecting directly access of instance variables in a class that does not define them in its initialize method.

Constant Summary

Constants inherited from BaseDetector

BaseDetector::DEFAULT_EXCLUDE_SET, BaseDetector::EXCLUDE_KEY

Instance Attribute Summary

Attributes inherited from BaseDetector

#config, #context

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseDetector

#config_for, configuration_keys, default_config, descendants, #enabled?, #exception?, #expression, inherited, #initialize, #run, #smell_type, smell_type, #smell_warning, #source_line, to_detector, todo_configuration_for, #value

Constructor Details

This class inherits a constructor from Reek::SmellDetectors::BaseDetector

Class Method Details

.contextsObject



13
14
15
# File 'lib/reek/smell_detectors/instance_variable_assumption.rb', line 13

def self.contexts
  [:class]
end

Instance Method Details

#build_smell_warning(assumption) ⇒ Object (private)



36
37
38
39
40
41
42
43
# File 'lib/reek/smell_detectors/instance_variable_assumption.rb', line 36

def build_smell_warning(assumption)
  message = "assumes too much for instance variable '#{assumption}'"

  smell_warning(
    lines: [source_line],
    message: message,
    parameters: { assumption: assumption.to_s })
end

#method_expressionsObject (private)



32
33
34
# File 'lib/reek/smell_detectors/instance_variable_assumption.rb', line 32

def method_expressions
  @method_expressions ||= context.node_instance_methods
end

#sniffArray<SmellWarning>

Checks klass for instance variables assumptions.

Returns:



22
23
24
25
26
27
28
# File 'lib/reek/smell_detectors/instance_variable_assumption.rb', line 22

def sniff
  assumptions = (variables_from_context - variables_from_initializers).uniq

  assumptions.map do |assumption|
    build_smell_warning(assumption)
  end
end

#variables_from_contextObject (private)



55
56
57
58
59
# File 'lib/reek/smell_detectors/instance_variable_assumption.rb', line 55

def variables_from_context
  method_expressions.map do |method|
    method.each_node(:ivar, [:or_asgn]).map(&:name)
  end.flatten
end

#variables_from_initializeObject (private)



51
52
53
# File 'lib/reek/smell_detectors/instance_variable_assumption.rb', line 51

def variables_from_initialize
  method_expressions.select { |method| method.name == :initialize }
end

#variables_from_initializersObject (private)



45
46
47
48
49
# File 'lib/reek/smell_detectors/instance_variable_assumption.rb', line 45

def variables_from_initializers
  variables_from_initialize.map do |method|
    method.each_node(:ivasgn).map(&:name)
  end.flatten
end