Skip to content

Commit 1dc2a40

Browse files
authored
Support inspecting BasicObject (#541)
1 parent 110e4a3 commit 1dc2a40

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

lib/irb/color_printer.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44

55
module IRB
66
class ColorPrinter < ::PP
7+
METHOD_IS_A = Object.instance_method(:is_a?)
8+
METHOD_RESPOND_TO = Object.instance_method(:respond_to?)
9+
METHOD_INSPECT = Object.instance_method(:inspect)
10+
711
class << self
812
def pp(obj, out = $>, width = screen_width)
913
q = ColorPrinter.new(out, width)
@@ -22,9 +26,11 @@ def screen_width
2226
end
2327

2428
def pp(obj)
25-
if obj.is_a?(String)
29+
if METHOD_IS_A.bind(obj).call(String)
2630
# Avoid calling Ruby 2.4+ String#pretty_print that splits a string by "\n"
2731
text(obj.inspect)
32+
elsif !METHOD_RESPOND_TO.bind(obj).call(:inspect)
33+
text(METHOD_INSPECT.bind(obj).call)
2834
else
2935
super
3036
end

test/irb/test_context.rb

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,6 @@ def test_output_to_pipe
129129
failed: [
130130
[false, "BasicObject.new", /#<NoMethodError: undefined method `to_s' for/],
131131
[:p, "class Foo; undef inspect ;end; Foo.new", /#<NoMethodError: undefined method `inspect' for/],
132-
[true, "BasicObject.new", /#<NoMethodError: undefined method `is_a\?' for/],
133132
[:yaml, "BasicObject.new", /#<NoMethodError: undefined method `inspect' for/],
134133
[:marshal, "[Object.new, Class.new]", /#<TypeError: can't dump anonymous class #<Class:/]
135134
]
@@ -150,6 +149,19 @@ def test_output_to_pipe
150149
end
151150
end
152151

152+
def test_object_inspection_handles_basic_object
153+
verbose, $VERBOSE = $VERBOSE, nil
154+
irb = IRB::Irb.new(IRB::WorkSpace.new(Object.new), TestInputMethod.new(["BasicObject.new"]))
155+
out, err = capture_output do
156+
irb.eval_input
157+
end
158+
assert_empty err
159+
assert_not_match(/NoMethodError/, out)
160+
assert_match(/#<BasicObject:.*>/, out)
161+
ensure
162+
$VERBOSE = verbose
163+
end
164+
153165
def test_object_inspection_falls_back_to_kernel_inspect_when_errored
154166
verbose, $VERBOSE = $VERBOSE, nil
155167
main = Object.new

0 commit comments

Comments
 (0)