Skip to content

Commit 83702f7

Browse files
byrootmatzbot
authored andcommitted
[ruby/pp] Handle BasicObject
Right now attempting to pretty print a BasicObject or any other object lacking a few core Object methods will result in an error ``` Error: test_basic_object(PPTestModule::PPInspectTest): NoMethodError: undefined method `is_a?' for an instance of BasicObject lib/pp.rb:192:in `pp' lib/pp.rb:97:in `block in pp' lib/pp.rb:158:in `guard_inspect_key' lib/pp.rb:97:in `pp' test/test_pp.rb:131:in `test_basic_object' 128: 129: def test_basic_object 130: a = BasicObject.new => 131: assert_match(/\A#<BasicObject:0x[\da-f]+>\n\z/, PP.pp(a, ''.dup)) 132: end 133: end 134: ``` With some fairly small changes we can fallback to `Object#inspect` which is better than an error. ruby/pp@4e9f6c2de0
1 parent 107a4da commit 83702f7

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

lib/pp.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def pop_inspect_key(id)
189189
def pp(obj)
190190
# If obj is a Delegator then use the object being delegated to for cycle
191191
# detection
192-
obj = obj.__getobj__ if defined?(::Delegator) and obj.is_a?(::Delegator)
192+
obj = obj.__getobj__ if defined?(::Delegator) and ::Delegator === obj
193193

194194
if check_inspect_key(obj)
195195
group {obj.pretty_print_cycle self}
@@ -198,7 +198,11 @@ def pp(obj)
198198

199199
begin
200200
push_inspect_key(obj)
201-
group {obj.pretty_print self}
201+
group do
202+
obj.pretty_print self
203+
rescue NoMethodError
204+
text Kernel.instance_method(:inspect).bind_call(obj)
205+
end
202206
ensure
203207
pop_inspect_key(obj) unless PP.sharing_detection
204208
end

test/test_pp.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,11 @@ def a.to_s() "aaa" end
125125
result = PP.pp(a, ''.dup)
126126
assert_equal("#{a.inspect}\n", result)
127127
end
128+
129+
def test_basic_object
130+
a = BasicObject.new
131+
assert_match(/\A#<BasicObject:0x[\da-f]+>\n\z/, PP.pp(a, ''.dup))
132+
end
128133
end
129134

130135
class PPCycleTest < Test::Unit::TestCase

0 commit comments

Comments
 (0)