Class: Rubocop::Cop::Lint::UnusedLocalVariable

Inherits:
Cop
  • Object
show all
Includes:
VariableInspector
Defined in:
lib/rubocop/cop/lint/unused_local_variable.rb

Overview

This cop looks for unused local variables in each scope. Actually this is a mimic of the warning "assigned but unused variable - foo" from ruby -cw.

Constant Summary collapse

MSG =
'Assigned but unused variable - %s'
TYPES_TO_ACCEPT_UNUSED =
(ARGUMENT_DECLARATION_TYPES - [:shadowarg]).freeze

Constants included from VariableInspector

VariableInspector::ARGUMENT_DECLARATION_TYPES, VariableInspector::SCOPE_TYPES, VariableInspector::VARIABLE_ASSIGNMENT_TYPES, VariableInspector::VARIABLE_DECLARATION_TYPES, VariableInspector::VARIABLE_USE_TYPES

Instance Attribute Summary

Attributes inherited from Cop

#autocorrect, #corrections, #debug, #disabled_lines, #offences

Instance Method Summary collapse

Methods included from VariableInspector

#after_declaring_variable, #after_entering_scope, #before_declaring_variable, #before_entering_scope, #before_leaving_scope, #inspect_variables, #inspect_variables_in_scope, #process_named_captures, #process_node, #process_variable_assignment, #variable_table

Methods inherited from Cop

#add_offence, all, #autocorrect_action, cop_name, cop_type, #do_autocorrect, #ignore_node, inherited, #initialize, lint?, #name, rails?, style?

Constructor Details

This class inherits a constructor from Rubocop::Cop::Cop

Instance Method Details

#after_leaving_scope(scope) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/rubocop/cop/lint/unused_local_variable.rb', line 20

def after_leaving_scope(scope)
  scope.variable_entries.each_value do |entry|
    next if entry.used?
    next if TYPES_TO_ACCEPT_UNUSED.include?(entry.node.type)
    next if entry.name.to_s.start_with?('_')
    message = sprintf(MSG, entry.name)
    add_offence(:warning, entry.node.loc.expression, message)
  end
end

#investigate(processed_source) ⇒ Object



16
17
18
# File 'lib/rubocop/cop/lint/unused_local_variable.rb', line 16

def investigate(processed_source)
  inspect_variables(processed_source.ast)
end