diff --git a/lib/text-table.rb b/lib/text-table.rb index 0b71cd4..3820774 100644 --- a/lib/text-table.rb +++ b/lib/text-table.rb @@ -1,3 +1,4 @@ +$KCODE = 'u' %w(table row cell enumerable symbol).each do |lib| require File.join(File.dirname(__FILE__), 'text-table', lib) -end \ No newline at end of file +end diff --git a/lib/text-table/cell.rb b/lib/text-table/cell.rb index f8298a0..e29e85f 100644 --- a/lib/text-table/cell.rb +++ b/lib/text-table/cell.rb @@ -5,7 +5,7 @@ class Cell # The object whose to_s method is called when rendering the cell. # attr_accessor :value - + # Text alignment. Acceptable values are :left (default), # :center and :right # @@ -23,14 +23,28 @@ def initialize(options = {}) #:nodoc: @colspan = options[:colspan] || 1 end + def text_width + char_count + value.chars.count { |c| c.bytesize > 2 } + end + + def char_count + @char_count ||= value.split('').length + end + def to_s #:nodoc: + if RUBY_VERSION < '1.9' + len = value.bytesize + cell_width - text_width + else + len = value.length + cell_width - text_width + end + ([' ' * table.horizontal_padding]*2).join case align when :left - value.ljust cell_width + value.ljust len when :right - value.rjust cell_width + value.rjust len when :center - value.center cell_width + value.center len end end @@ -48,4 +62,4 @@ def cell_width #:nodoc: end end -end \ No newline at end of file +end diff --git a/lib/text-table/table.rb b/lib/text-table/table.rb index 427e611..d068d84 100644 --- a/lib/text-table/table.rb +++ b/lib/text-table/table.rb @@ -153,7 +153,7 @@ def all_text_table_rows #:nodoc: def column_widths #:nodoc: @column_widths ||= \ all_text_table_rows.reject {|row| row.cells == :separator}.map do |row| - row.cells.map {|cell| [(cell.value.length/cell.colspan.to_f).ceil] * cell.colspan}.flatten + row.cells.map {|cell| [(cell.text_width/cell.colspan.to_f).ceil] * cell.colspan}.flatten end.transpose.map(&:max) end diff --git a/spec/integration/multibyte_spec.rb b/spec/integration/multibyte_spec.rb new file mode 100644 index 0000000..8b17bf7 --- /dev/null +++ b/spec/integration/multibyte_spec.rb @@ -0,0 +1,27 @@ +# coding: utf-8 +require 'integration_helper' + +describe Text::Table do + let(:table) { Text::Table.new :rows => rows } + let(:rows) do + [ + ["Hello"], + ["こんにちは"], + ["مرحبا"], + ["안녕하세요"], + ] + end + + subject { table.to_s } + + describe 'rows' do + it { should == deindent(%q{ + +------------+ + | Hello | + | こんにちは | + | مرحبا | + | 안녕하세요 | + +------------+ + }) } + end +end