Class: RBI::Rewriters::NestTopLevelMembers

Inherits:
Visitor
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/rbi/rewriters/nest_top_level_members.rb

Overview

This rewriter moves top-level members into a top-level Object class

Example: ~~~rb def foo; end attr_reader :bar ~~~

will be rewritten to:

~~~rb class Object

def foo; end
attr_reader :bar

end ~~~

Instance Method Summary collapse

Methods inherited from Visitor

#visit_all, #visit_file

Constructor Details

#initializeNestTopLevelMembers

Returns a new instance of NestTopLevelMembers.



26
27
28
29
30
# File 'lib/rbi/rewriters/nest_top_level_members.rb', line 26

def initialize
  super

  @top_level_object_class = T.let(nil, T.nilable(Class))
end

Instance Method Details

#visit(node) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rbi/rewriters/nest_top_level_members.rb', line 33

def visit(node)
  return unless node

  case node
  when Tree
    visit_all(node.nodes.dup)
  else
    scope = node.parent_scope
    unless scope
      parent = node.parent_tree
      raise unless parent

      node.detach

      unless @top_level_object_class
        @top_level_object_class = Class.new("Object")
        parent.nodes << @top_level_object_class
      end

      @top_level_object_class << node
    end
  end
end