Class: RBI::Rewriters::NestSingletonMethods

Inherits:
Visitor
  • Object
show all
Defined in:
lib/rbi/rewriters/nest_singleton_methods.rb

Instance Method Summary collapse

Methods inherited from Visitor

#visit_all, #visit_file

Instance Method Details

#visit(node) ⇒ Object

: (Node? node) -> void



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rbi/rewriters/nest_singleton_methods.rb', line 9

def visit(node)
  return unless node

  case node
  when Tree
    singleton_class = SingletonClass.new

    # Collect singleton methods and remaining nodes in a single pass,
    # avoiding O(n) Array#delete calls from `detach` in a loop.
    remaining = []
    node.nodes.each do |child|
      visit(child)
      if child.is_a?(Method) && child.is_singleton
        child.parent_tree = nil
        child.is_singleton = false
        singleton_class << child
      else
        remaining << child
      end
    end

    unless singleton_class.empty?
      node.nodes.replace(remaining)
      node << singleton_class
    end
  end
end