Skip to content

Commit 8d13df2

Browse files
aycabtak0kubun
andcommitted
Stringify when a non-object is passed to PP#text
If a nested object is passed to #pp, it may be sometimes passed to the #text method as an object without being stringified. This is fixed on the Ruby main repository; ruby/ruby@433a3be but it was a bug of Ripper so still needs this workaround for using irb as a gem on Ruby 3.0.0 or earlier. Co-authored-by: k0kubun <takashikkbn@gmail.com>
1 parent 212897d commit 8d13df2

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

lib/irb/color_printer.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,12 @@ def self.pp(obj, out = $>, width = 79)
1010
out
1111
end
1212

13-
def text(str, width = str.length)
13+
def text(str, width = nil)
14+
unless str.is_a?(String)
15+
str = str.inspect
16+
end
17+
width ||= str.length
18+
1419
case str
1520
when /\A#</, '=', '>'
1621
super(Color.colorize(str, [:GREEN]), width)

test/irb/test_color.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# frozen_string_literal: false
22
require 'test/unit'
33
require 'irb/color'
4+
require 'irb/color_printer'
45
require 'rubygems'
56
require 'stringio'
67

@@ -152,6 +153,20 @@ def test_colorize_code_complete_false
152153
end
153154
end
154155

156+
def test_color_printer
157+
unless ripper_lexer_scan_supported?
158+
skip 'Ripper::Lexer#scan is supported in Ruby 2.7+'
159+
end
160+
{
161+
1 => "#{BLUE}#{BOLD}1#{CLEAR}",
162+
Struct.new('IRBTestColorPrinter', :a).new('test') => "#{GREEN}#<struct Struct::IRBTestColorPrinter#{CLEAR} a#{GREEN}=#{CLEAR}#{RED}#{BOLD}\"#{CLEAR}#{RED}test#{CLEAR}#{RED}#{BOLD}\"#{CLEAR}#{GREEN}>#{CLEAR}",
163+
Ripper::Lexer.new('1').scan => "[#{GREEN}#<Ripper::Lexer::Elem:#{CLEAR} on_int@1:0 END token: #{RED}#{BOLD}\"#{CLEAR}#{RED}1#{CLEAR}#{RED}#{BOLD}\"#{CLEAR}#{GREEN}>#{CLEAR}]",
164+
}.each do |object, result|
165+
actual = with_term { IRB::ColorPrinter.pp(object, '') }
166+
assert_equal(result, actual, "Case: IRB::ColorPrinter.pp(#{object.inspect}, '')")
167+
end
168+
end
169+
155170
def test_inspect_colorable
156171
{
157172
1 => true,
@@ -184,6 +199,10 @@ def complete_option_supported?
184199
Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7.0')
185200
end
186201

202+
def ripper_lexer_scan_supported?
203+
Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7.0')
204+
end
205+
187206
def with_term
188207
stdout = $stdout
189208
io = StringIO.new

0 commit comments

Comments
 (0)