Module: RuboCop::AST::ConstantNode

Included in:
CasgnNode, ConstNode
Defined in:
lib/rubocop/ast/node/mixin/constant_node.rb

Overview

Common functionality for nodes that deal with constants: ‘const`, `casgn`.

Instance Method Summary collapse

Instance Method Details

#absolute?Boolean

Returns if the constant starts with ‘::` (aka s(:cbase)).

Returns:

  • (Boolean)

    if the constant starts with ‘::` (aka s(:cbase))



27
28
29
30
31
# File 'lib/rubocop/ast/node/mixin/constant_node.rb', line 27

def absolute?
  return false unless namespace

  each_path.first.cbase_type?
end

#each_path(&block) ⇒ Object

Yield nodes for the namespace

For `::Foo::Bar::BAZ` => yields:
   s(:cbase), then
   s(:const, :Foo), then
   s(:const, s(:const, :Foo), :Bar)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rubocop/ast/node/mixin/constant_node.rb', line 44

def each_path(&block)
  return to_enum(__method__) unless block

  descendants = []
  last = self
  loop do
    last = last.children.first
    break if last.nil?

    descendants << last
    break unless last.const_type?
  end
  descendants.reverse_each(&block)

  self
end

#module_name?Boolean Also known as: class_name?

If the constant is a Module / Class, according to the standard convention. Note: some classes might have uppercase in which case this method

returns false

Returns:

  • (Boolean)

    if the constant is a Module / Class, according to the standard convention. Note: some classes might have uppercase in which case this method

    returns false
    


21
22
23
# File 'lib/rubocop/ast/node/mixin/constant_node.rb', line 21

def module_name?
  short_name.match?(/[[:lower:]]/)
end

#namespaceNode?

Returns the node associated with the scope (e.g. cbase, const, …).

Returns:

  • (Node, nil)

    the node associated with the scope (e.g. cbase, const, …)



9
10
11
# File 'lib/rubocop/ast/node/mixin/constant_node.rb', line 9

def namespace
  children[0]
end

#relative?Boolean

Returns if the constant does not start with ‘::` (aka s(:cbase)).

Returns:

  • (Boolean)

    if the constant does not start with ‘::` (aka s(:cbase))



34
35
36
# File 'lib/rubocop/ast/node/mixin/constant_node.rb', line 34

def relative?
  !absolute?
end

#short_nameSymbol

Returns the demodulized name of the constant: “::Foo::Bar” => :Bar.

Returns:

  • (Symbol)

    the demodulized name of the constant: “::Foo::Bar” => :Bar



14
15
16
# File 'lib/rubocop/ast/node/mixin/constant_node.rb', line 14

def short_name
  children[1]
end