Skip to content

Commit 80a18e8

Browse files
Fryguynobu
authored andcommitted
[ruby/pp] Support new instance_variables_to_inspect method from Ruby core
This supports the new `instance_variables_to_inspect` method from Ruby core that was added in ruby#13555. If `instance_variables_to_inspect` is defined, then `pretty_print_instance_variables` will use it. Additionally, this commit introduces tests for both `pretty_print_instance_variables` and `instance_variables_to_inspect`. ruby/pp@9cea466c95
1 parent 8cc5e5c commit 80a18e8

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

lib/pp.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,8 @@ def pretty_print_cycle(q)
399399
# This method should return an array of names of instance variables as symbols or strings as:
400400
# +[:@a, :@b]+.
401401
def pretty_print_instance_variables
402-
instance_variables.sort
402+
ivars = respond_to?(:instance_variables_to_inspect) ? instance_variables_to_inspect : instance_variables
403+
ivars.sort
403404
end
404405

405406
# Is #inspect implementation using #pretty_print.

test/test_pp.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,20 @@ def a.to_s() "aaa" end
130130
assert_equal("#{a.inspect}\n", result)
131131
end
132132

133+
def test_iv_hiding
134+
a = Object.new
135+
def a.pretty_print_instance_variables() [:@b] end
136+
a.instance_eval { @a = "aaa"; @b = "bbb" }
137+
assert_match(/\A#<Object:0x[\da-f]+ @b="bbb">\n\z/, PP.pp(a, ''.dup))
138+
end
139+
140+
def test_iv_hiding_via_ruby
141+
a = Object.new
142+
def a.instance_variables_to_inspect() [:@b] end
143+
a.instance_eval { @a = "aaa"; @b = "bbb" }
144+
assert_match(/\A#<Object:0x[\da-f]+ @b="bbb">\n\z/, PP.pp(a, ''.dup))
145+
end
146+
133147
def test_basic_object
134148
a = BasicObject.new
135149
assert_match(/\A#<BasicObject:0x[\da-f]+>\n\z/, PP.pp(a, ''.dup))

0 commit comments

Comments
 (0)