From 7a0894793ef359679aedad3836d593a83bb4a0a4 Mon Sep 17 00:00:00 2001 From: Oskar Eichler Date: Mon, 31 Aug 2026 00:57:40 +0200 Subject: [PATCH] Propagate errors from custom pretty printers --- lib/pp.rb | 6 +++++- test/test_pp.rb | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/pp.rb b/lib/pp.rb index 798a4f4..ad3cf78 100644 --- a/lib/pp.rb +++ b/lib/pp.rb @@ -210,7 +210,11 @@ def pp(obj) guard_inspect(obj) do group do obj.pretty_print self - rescue NoMethodError + rescue NoMethodError => error + raise unless + error.name == :pretty_print && + error.receiver.equal?(obj) && + !PP.mcall(obj, Kernel, :respond_to?, :pretty_print) text Kernel.instance_method(:inspect).bind_call(obj) end end diff --git a/test/test_pp.rb b/test/test_pp.rb index 922ed37..2469f6b 100644 --- a/test/test_pp.rb +++ b/test/test_pp.rb @@ -94,6 +94,12 @@ class PrettyPrintInspectWithoutPrettyPrint alias inspect pretty_print_inspect end +class PrettyPrintRaises + def pretty_print(q) + self.missing_from_pretty_print + end +end + class PPInspectTest < Test::Unit::TestCase def test_hasinspect a = HasInspect.new(1) @@ -157,6 +163,11 @@ def test_basic_object a = BasicObject.new assert_match(/\A#\n\z/, PP.pp(a, ''.dup)) end + + def test_pretty_print_error + error = assert_raise(NoMethodError) { PP.pp(PrettyPrintRaises.new, ''.dup) } + assert_equal(:missing_from_pretty_print, error.name) + end end class PPCycleTest < Test::Unit::TestCase