Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions lib/table_print/formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
4 changes: 4 additions & 0 deletions spec/formatter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down