Class: Rubocop::Cop::VariableInspector::Scope

Inherits:
Object
  • Object
show all
Defined in:
lib/rubocop/cop/variable_inspector/scope.rb

Overview

A Scope represents a context of local variable visibility. This is a place where local variables belong to. A scope instance holds a scope node and variable entries.

Defined Under Namespace

Classes: ASTScanner

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(node) ⇒ Scope

Returns a new instance of Scope.



12
13
14
15
16
17
18
19
20
21
# File 'lib/rubocop/cop/variable_inspector/scope.rb', line 12

def initialize(node)
  # Accept begin node for top level scope.
  unless SCOPE_TYPES.include?(node.type) || node.type == :begin
    fail ArgumentError,
         "Node type must be any of #{SCOPE_TYPES}, " \
         "passed #{node.type}"
  end
  @node = node
  @variables = {}
end

Instance Attribute Details

#nodeObject (readonly)

Returns the value of attribute node.



10
11
12
# File 'lib/rubocop/cop/variable_inspector/scope.rb', line 10

def node
  @node
end

#variablesObject (readonly)

Returns the value of attribute variables.



10
11
12
# File 'lib/rubocop/cop/variable_inspector/scope.rb', line 10

def variables
  @variables
end

Instance Method Details

#==(other) ⇒ Object



23
24
25
# File 'lib/rubocop/cop/variable_inspector/scope.rb', line 23

def ==(other)
  @node.equal?(other.node)
end

#ancestors_of_node(target_node) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/rubocop/cop/variable_inspector/scope.rb', line 38

def ancestors_of_node(target_node)
  ASTScanner.scan(@node) do |scanning_node, ancestor_nodes|
    return ancestor_nodes[1..-1] if scanning_node.equal?(target_node)
  end

  fail "Node #{target_node} is not found in scope #{@node}"
end

#body_nodeObject



27
28
29
30
31
32
33
34
35
36
# File 'lib/rubocop/cop/variable_inspector/scope.rb', line 27

def body_node
  child_index = case @node.type
                when :top_level           then 0
                when :module, :sclass     then 1
                when :def, :class, :block then 2
                when :defs                then 3
                end

  @node.children[child_index]
end