Skip to content

Commit 5b5d483

Browse files
authored
Ensure the thread local state is always set up. (#38)
1 parent 9fc3a98 commit 5b5d483

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

lib/pp.rb

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,24 @@ def pop_inspect_key(id)
183183
Thread.current[:__recursive_key__][:inspect].delete id
184184
end
185185

186+
private def guard_inspect(object)
187+
recursive_state = Thread.current[:__recursive_key__]
188+
189+
if recursive_state && recursive_state.key?(:inspect)
190+
begin
191+
push_inspect_key(object)
192+
yield
193+
ensure
194+
pop_inspect_key(object) unless PP.sharing_detection
195+
end
196+
else
197+
guard_inspect_key do
198+
push_inspect_key(object)
199+
yield
200+
end
201+
end
202+
end
203+
186204
# Adds +obj+ to the pretty printing buffer
187205
# using Object#pretty_print or Object#pretty_print_cycle.
188206
#
@@ -198,15 +216,12 @@ def pp(obj)
198216
return
199217
end
200218

201-
begin
202-
push_inspect_key(obj)
219+
guard_inspect(obj) do
203220
group do
204221
obj.pretty_print self
205222
rescue NoMethodError
206223
text Kernel.instance_method(:inspect).bind_call(obj)
207224
end
208-
ensure
209-
pop_inspect_key(obj) unless PP.sharing_detection
210225
end
211226
end
212227

test/test_pp.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,22 @@ def test_hash_in_array
243243
assert_equal("[{}]", PP.singleline_pp([->(*a){a.last.clear}.ruby2_keywords.call(a: 1)], ''.dup))
244244
assert_equal("[{}]", PP.singleline_pp([Hash.ruby2_keywords_hash({})], ''.dup))
245245
end
246+
247+
def test_direct_pp
248+
buffer = String.new
249+
250+
a = []
251+
a << a
252+
253+
# Isolate the test from any existing Thread.current[:__recursive_key__][:inspect].
254+
Thread.new do
255+
q = PP::SingleLine.new(buffer)
256+
q.pp(a)
257+
q.flush
258+
end.join
259+
260+
assert_equal("[[...]]", buffer)
261+
end
246262
end
247263

248264
class PPDelegateTest < Test::Unit::TestCase

0 commit comments

Comments
 (0)