Class: Reek::SmellDetectors::UnusedPrivateMethod

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

Overview

Classes should use their private methods. Otherwise this is dead code which is confusing and bad for maintenance.

See Unused-Private-Method for details.

Defined Under Namespace

Classes: Hit

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, 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



30
31
32
# File 'lib/reek/smell_detectors/unused_private_method.rb', line 30

def self.contexts
  [:class]
end

.default_configObject



14
15
16
# File 'lib/reek/smell_detectors/unused_private_method.rb', line 14

def self.default_config
  super.merge(SmellConfiguration::ENABLED_KEY => false)
end

Instance Method Details

#hitsArray<Hit> (private)

Returns:



52
53
54
55
56
# File 'lib/reek/smell_detectors/unused_private_method.rb', line 52

def hits
  unused_private_methods.filter_map do |defined_method|
    Hit.new(defined_method) unless ignore_method?(defined_method)
  end
end

#ignore_method?(method) ⇒ Boolean (private)

Parameters:

Returns:

  • (Boolean)


75
76
77
78
79
80
81
82
# File 'lib/reek/smell_detectors/unused_private_method.rb', line 75

def ignore_method?(method)
  # ignore_contexts will be e.g. ["Foo::Smelly#my_method", "..."]
  ignore_contexts = value(EXCLUDE_KEY, context)
  ignore_contexts.any? do |ignore_context|
    full_name = "#{method.parent.full_name}##{method.name}"
    full_name[ignore_context]
  end
end

#sniffArray<SmellWarning>

Returns:



37
38
39
40
41
42
43
44
45
# File 'lib/reek/smell_detectors/unused_private_method.rb', line 37

def sniff
  hits.map do |hit|
    name = hit.name
    smell_warning(
      lines: [hit.line],
      message: "has the unused private instance method '#{name}'",
      parameters: { name: name.to_s })
  end
end

#unused_private_methodsArray<Context::MethodContext] (private)

Returns Array<Context::MethodContext].

Returns:



61
62
63
64
65
66
67
68
69
# File 'lib/reek/smell_detectors/unused_private_method.rb', line 61

def unused_private_methods
  defined_private_methods = context.defined_instance_methods(visibility: :private)
  called_method_names     = context.instance_method_calls.map(&:name)
  called_method_names.concat(context.instance_method_names_via_to_call)

  defined_private_methods.reject do |defined_method|
    called_method_names.include?(defined_method.name)
  end
end