diff --git a/lib/pp.rb b/lib/pp.rb index 798a4f4..1a6bf26 100644 --- a/lib/pp.rb +++ b/lib/pp.rb @@ -82,6 +82,9 @@ def PP.width_for(out) _, width = out.winsize rescue LoadError, NoMethodError, SystemCallError end + # winsize can report 0 for a non-tty or constrained device; treat that + # like a missing width so we fall back to COLUMNS / 80 instead of -1. + width = nil unless width&.nonzero? (width || ENV['COLUMNS']&.to_i&.nonzero? || 80) - 1 end @@ -220,7 +223,8 @@ def pp(obj) # # group(1, '#<' + obj.class.name, '>') { ... } def object_group(obj, &block) # :yield: - group(1, '#<' + obj.class.name, '>', &block) + # Anonymous classes have a nil #name; #to_s still yields a usable label. + group(1, '#<' + (obj.class.name || obj.class.to_s), '>', &block) end # A convenience method, like object_group, but also reformats the Object's diff --git a/test/test_pp.rb b/test/test_pp.rb index 922ed37..9040eba 100644 --- a/test/test_pp.rb +++ b/test/test_pp.rb @@ -46,6 +46,20 @@ def test_range assert_equal("false..false\n", PP.pp(false..false, "".dup)) assert_equal("nil..nil\n", PP.pp(nil..nil, "".dup)) end + + def test_width_for_zero_winsize + out = Object.new + def out.winsize; [24, 0]; end + assert_equal(79, PP.width_for(out)) + end + + def test_object_group_anonymous_class + obj = Class.new.new + q = PP.new("".dup) + q.object_group(obj) { q.text "x" } + q.flush + assert_match(/\A#<#x>\z/, q.output) + end end class HasInspect