Skip to content

Commit

Permalink
Stringify when a non-object is passed to PP#text
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
aycabta committed Jan 4, 2021
1 parent 212897d commit 1a60403
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
11 changes: 8 additions & 3 deletions lib/irb/color_printer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,17 @@ def self.pp(obj, out = $>, width = 79)
out
end

def text(str, width = str.length)
def text(str, width = nil)
case str
when /\A#</, '=', '>'
super(Color.colorize(str, [:GREEN]), width)
super(Color.colorize(str, [:GREEN]), str.length)
else
super(Color.colorize_code(str, ignore_error: true), width)
begin
super(Color.colorize_code(str, ignore_error: true), str.length)
rescue TypeError
str = str.inspect
super(Color.colorize(str, [:GREEN]), str.length)
end
end
end
end
Expand Down
18 changes: 18 additions & 0 deletions test/irb/test_color.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: false
require 'test/unit'
require 'irb/color'
require 'irb/color_printer'
require 'rubygems'
require 'stringio'

Expand Down Expand Up @@ -152,6 +153,19 @@ def test_colorize_code_complete_false
end
end

def test_color_printer
unless ripper_lexer_scan_supported?
skip 'Ripper::Lexer#scan is supported in Ruby 2.7+'
end
{
1 => "#{BLUE}#{BOLD}1#{CLEAR}",
Ripper::Lexer.new('1').scan => "[#{GREEN}#<Ripper::Lexer::Elem:#{CLEAR} on_int@1:0 #{GREEN}END#{CLEAR} token: #{RED}#{BOLD}\"#{CLEAR}#{RED}1#{CLEAR}#{RED}#{BOLD}\"#{CLEAR}#{GREEN}>#{CLEAR}]",
}.each do |object, result|
actual = with_term { IRB::ColorPrinter.pp(object, '') }
assert_equal(result, actual, "Case: IRB::ColorPrinter.pp(#{object.inspect}, '')")
end
end

def test_inspect_colorable
{
1 => true,
Expand Down Expand Up @@ -184,6 +198,10 @@ def complete_option_supported?
Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7.0')
end

def ripper_lexer_scan_supported?
Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7.0')
end

def with_term
stdout = $stdout
io = StringIO.new
Expand Down

0 comments on commit 1a60403

Please sign in to comment.