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