Class: RuboCop::Cop::VariableForce::Scope

Inherits:
Object
  • Object
show all
Defined in:
lib/rubocop/cop/variable_force/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.

Constant Summary collapse

OUTER_SCOPE_CHILD_INDICES =
{
  defs:   0..0,
  module: 0..0,
  class:  0..1,
  sclass: 0..0,
  block:  0..0
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(node) ⇒ Scope

Returns a new instance of Scope.



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rubocop/cop/variable_force/scope.rb', line 21

def initialize(node)
  unless SCOPE_TYPES.include?(node.type)
    # Accept any node type for top level scope
    if node.parent
      raise ArgumentError,
            "Node type must be any of #{SCOPE_TYPES}, " \
            "passed #{node.type}"
    end
    @naked_top_level = true
  end
  @node = node
  @variables = {}
end

Instance Attribute Details

#naked_top_levelObject (readonly) Also known as: naked_top_level?

Returns the value of attribute naked_top_level.



18
19
20
# File 'lib/rubocop/cop/variable_force/scope.rb', line 18

def naked_top_level
  @naked_top_level
end

#nodeObject (readonly)

Returns the value of attribute node.



18
19
20
# File 'lib/rubocop/cop/variable_force/scope.rb', line 18

def node
  @node
end

#variablesObject (readonly)

Returns the value of attribute variables.



18
19
20
# File 'lib/rubocop/cop/variable_force/scope.rb', line 18

def variables
  @variables
end

Instance Method Details

#==(other) ⇒ Object



35
36
37
# File 'lib/rubocop/cop/variable_force/scope.rb', line 35

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

#body_nodeObject



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rubocop/cop/variable_force/scope.rb', line 47

def body_node
  if naked_top_level?
    node
  else
    child_index = case node.type
                  when :module, :sclass     then 1
                  when :def, :class, :block then 2
                  when :defs                then 3
                  end

    node.children[child_index]
  end
end

#each_node {|node| ... } ⇒ Object

Yields:



66
67
68
69
70
# File 'lib/rubocop/cop/variable_force/scope.rb', line 66

def each_node(&block)
  return to_enum(__method__) unless block_given?
  yield node if naked_top_level?
  scan_node(node, &block)
end

#include?(target_node) ⇒ Boolean

Returns:

  • (Boolean)


61
62
63
64
# File 'lib/rubocop/cop/variable_force/scope.rb', line 61

def include?(target_node)
  !belong_to_outer_scope?(target_node) &&
    !belong_to_inner_scope?(target_node)
end

#nameObject



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

def name
  # TODO: Add an else clause
  case @node.type
  when :def  then @node.children[0]
  when :defs then @node.children[1]
  end
end