From f204df3aad7a7fd51d2838f199f0b4c2c2799170 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Sun, 5 Sep 2021 21:51:14 +0900 Subject: [PATCH 1/2] Get rid of hardcoded class name So that the `pp` method can work in inherited classes with that class. --- lib/pp.rb | 2 +- test/test_pp.rb | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/pp.rb b/lib/pp.rb index f04b7bf..40e83b2 100644 --- a/lib/pp.rb +++ b/lib/pp.rb @@ -93,7 +93,7 @@ def PP.width_for(out) # # PP.pp returns +out+. def PP.pp(obj, out=$>, width=width_for(out)) - q = PP.new(out, width) + q = new(out, width) q.guard_inspect_key {q.pp obj} q.flush #$pp = q diff --git a/test/test_pp.rb b/test/test_pp.rb index f6bd216..e51adde 100644 --- a/test/test_pp.rb +++ b/test/test_pp.rb @@ -245,4 +245,36 @@ def test_lasgn_literal end end +class PPInheritedTest < Test::Unit::TestCase + class PPSymbolHash < PP + def pp_hash(obj) + group(1, "{", "}") { + seplist(obj, nil, :each_pair) {|k, v| + case k + when Symbol + text k.inspect.delete_prefix(":") + text ":" + sep = " " + else + pp k + text "=>" + sep = "" + end + group(1) { + breakable sep + pp v + } + } + } + end + end + + def test_hash_override + obj = {k: 1, "": :null, "0": :zero, 100 => :ten} + assert_equal <<~EXPECT, PPSymbolHash.pp(obj, "".dup) + {k: 1, "": :null, "0": :zero, 100=>:ten} + EXPECT + end +end + end From 3fcf2d114215cf84a5ff9a9727813ba0dd2559fa Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Sun, 5 Sep 2021 22:19:48 +0900 Subject: [PATCH 2/2] Extract pp_hash_pair The method which prints single pair of a hash, to make extending pretty printing Hash easier, apart from Hash construct itself. --- lib/pp.rb | 17 +++++++++++------ test/test_pp.rb | 29 +++++++++++------------------ 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/lib/pp.rb b/lib/pp.rb index 40e83b2..1ec5a88 100644 --- a/lib/pp.rb +++ b/lib/pp.rb @@ -286,16 +286,21 @@ def pp_hash(obj) group(1, '{', '}') { seplist(obj, nil, :each_pair) {|k, v| group { - pp k - text '=>' - group(1) { - breakable '' - pp v - } + pp_hash_pair k, v } } } end + + # A pretty print for a pair of Hash + def pp_hash_pair(k, v) + pp k + text '=>' + group(1) { + breakable '' + pp v + } + end end include PPMethods diff --git a/test/test_pp.rb b/test/test_pp.rb index e51adde..2fdd5df 100644 --- a/test/test_pp.rb +++ b/test/test_pp.rb @@ -247,25 +247,18 @@ def test_lasgn_literal class PPInheritedTest < Test::Unit::TestCase class PPSymbolHash < PP - def pp_hash(obj) - group(1, "{", "}") { - seplist(obj, nil, :each_pair) {|k, v| - case k - when Symbol - text k.inspect.delete_prefix(":") - text ":" - sep = " " - else - pp k - text "=>" - sep = "" - end - group(1) { - breakable sep - pp v - } + def pp_hash_pair(k, v) + case k + when Symbol + text k.inspect.delete_prefix(":") + text ":" + group(1) { + breakable + pp v } - } + else + super + end end end