From 518dbf3175425f18f5cfa437dfc9acad108fe1b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ba=C4=8Dovsk=C3=BD?= Date: Fri, 20 Sep 2013 14:21:30 +0200 Subject: [PATCH] Added support for colorized values --- lib/table_print/formatter.rb | 8 ++++++-- spec/formatter_spec.rb | 4 ++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/table_print/formatter.rb b/lib/table_print/formatter.rb index 9b47aac..f40ab2b 100644 --- a/lib/table_print/formatter.rb +++ b/lib/table_print/formatter.rb @@ -25,7 +25,7 @@ def initialize(width) end def format(value) - padding = width - value.to_s.each_char.collect{|c| c.bytesize == 1 ? 1 : 2}.inject(0, &:+) + padding = width - strip_escape(value.to_s).each_char.collect{|c| c.bytesize == 1 ? 1 : 2}.inject(0, &:+) truncate(value) + (padding < 0 ? '' : " " * padding) end @@ -34,9 +34,13 @@ def truncate(value) return "" unless value value = value.to_s - return value unless value.length > width + return value unless strip_escape(value).length > width "#{value[0..width-4]}..." end + + def strip_escape(value) + value.gsub(%r{\e[^m]*m}, '') + end end end diff --git a/spec/formatter_spec.rb b/spec/formatter_spec.rb index 07c464c..fa8b9ad 100644 --- a/spec/formatter_spec.rb +++ b/spec/formatter_spec.rb @@ -53,6 +53,10 @@ @f.format("1234567890123456").should == "1234567..." end + it "truncate colorized values correctly" do + @f.format("\e[0;31;49masdf\e[0m").should == "\e[0;31;49masdf\e[0m " + end + it "uses an empty string in place of nils" do @f.format(nil).should == " " end