Skip to content

Commit

Permalink
Index singleton methods with class << self
Browse files Browse the repository at this point in the history
  • Loading branch information
andyw8 committed Oct 17, 2023
1 parent 9f8ca85 commit cd3547b
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
14 changes: 13 additions & 1 deletion lib/ruby_indexer/lib/ruby_indexer/visitor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ def initialize(index, parse_result, file_path)
@index = index
@file_path = file_path
@stack = T.let([], T::Array[String])
@singleton = T.let(false, T::Boolean)
@comments_by_line = T.let(
parse_result.comments.to_h do |c|
[c.location.start_line, c]
Expand All @@ -25,6 +26,13 @@ def visit_class_node(node)
add_class_entry(node)
end

sig { override.params(node: Prism::SingletonClassNode).void }
def visit_singleton_class_node(node)
@singleton = true
super
@singleton = false
end

sig { override.params(node: Prism::ModuleNode).void }
def visit_module_node(node)
add_module_entry(node)
Expand Down Expand Up @@ -126,7 +134,11 @@ def visit_def_node(node)
comments = collect_comments(node)
case node.receiver
when nil
@index << Entry::InstanceMethod.new(method_name, @file_path, node.location, comments, node.parameters)
@index << if @singleton
Entry::SingletonMethod.new(method_name, @file_path, node.location, comments, node.parameters)
else
Entry::InstanceMethod.new(method_name, @file_path, node.location, comments, node.parameters)
end
when Prism::SelfNode
@index << Entry::SingletonMethod.new(method_name, @file_path, node.location, comments, node.parameters)
end
Expand Down
34 changes: 33 additions & 1 deletion lib/ruby_indexer/test/method_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,39 @@ def bar
assert_entry("bar", Entry::InstanceMethod, "/fake/path/foo.rb:1-2:2-5")
end

def test_singleton_method_using_self_receiver
def test_singleton_method_using_class_self
index(<<~RUBY)
class Foo
class << self
def bar
end
end
def baz
end
end
RUBY

assert_entry("bar", Entry::SingletonMethod, "/fake/path/foo.rb:2-4:3-7")
assert_entry("baz", Entry::InstanceMethod, "/fake/path/foo.rb:6-2:7-5")
end

def test_singleton_method_using_class_self_with_nesting
index(<<~RUBY)
class Foo
class << self
class Nested
def bar
end
end
end
end
RUBY

assert_entry("bar", Entry::SingletonMethod, "/fake/path/foo.rb:3-6:4-9")
end

def test_singleton_method_using_class
index(<<~RUBY)
class Foo
def self.bar
Expand Down

0 comments on commit cd3547b

Please sign in to comment.