Skip to content

Commit

Permalink
[ruby/irb] Filter out top-level methods when using `ls
Browse files Browse the repository at this point in the history
<Class/Module>`
(ruby/irb#562)

Instead of always printing methods inherited from Class or Module, IRB by
default should filter them out unless `<Class/Module>` is specified to be
either of those.
  • Loading branch information
st0012 authored and matzbot committed Apr 24, 2023
1 parent 886986b commit 805899d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
7 changes: 5 additions & 2 deletions lib/irb/cmd/ls.rb
Expand Up @@ -39,8 +39,12 @@ def execute(*arg, grep: nil)
def dump_methods(o, klass, obj)
singleton_class = begin obj.singleton_class; rescue TypeError; nil end
dumped_mods = Array.new
ancestors = klass.ancestors
ancestors = ancestors.reject { |c| c >= Object } if klass < Object
singleton_ancestors = (singleton_class&.ancestors || []).reject { |c| c >= Class }

# singleton_class' ancestors should be at the front
maps = class_method_map(singleton_class&.ancestors || [], dumped_mods) + class_method_map(klass.ancestors, dumped_mods)
maps = class_method_map(singleton_ancestors, dumped_mods) + class_method_map(ancestors, dumped_mods)
maps.each do |mod, methods|
name = mod == singleton_class ? "#{klass}.methods" : "#{mod}#methods"
o.dump(name, methods)
Expand All @@ -49,7 +53,6 @@ def dump_methods(o, klass, obj)

def class_method_map(classes, dumped_mods)
dumped_methods = Array.new
classes = classes.reject { |mod| mod >= Object }
classes.map do |mod|
next if dumped_mods.include? mod

Expand Down
5 changes: 4 additions & 1 deletion test/irb/test_cmd.rb
Expand Up @@ -697,6 +697,8 @@ def test_ls_class
assert_empty err
assert_match(/C2.methods:\s+m3\s+m5\n/, out)
assert_match(/C2#methods:\s+m3\s+m4\n.*M1#methods:\s+m2\n.*C1#methods:\s+m1\n/, out)
assert_not_match(/Module#methods/, out)
assert_not_match(/Class#methods/, out)
end

def test_ls_module
Expand All @@ -716,8 +718,9 @@ def test_ls_module
)

assert_empty err
assert_match(/M2\.methods:\s+m4\nModule#methods:/, out)
assert_match(/M2\.methods:\s+m4\n/, out)
assert_match(/M2#methods:\s+m1\s+m3\n.*M1#methods:\s+m2\n/, out)
assert_not_match(/Module#methods/, out)
end

def test_ls_instance
Expand Down

0 comments on commit 805899d

Please sign in to comment.