lib/terminal-table/cell.rb in terminal-table-1.4.3 vs lib/terminal-table/cell.rb in terminal-table-1.4.4
- old
+ new
@@ -12,42 +12,77 @@
# Cell value.
attr_reader :value
##
- # Cell alignment.
-
- attr_reader :alignment
-
- ##
# Column span.
attr_reader :colspan
##
- # Initialize with _width_ and _options_.
+ # Initialize with _options_.
- def initialize width, options = nil
- @width = width
+ def initialize options = nil
@value, options = options, {} unless Hash === options
@value = options.fetch :value, value
- @alignment = options.fetch :alignment, :left
+ @alignment = options.fetch :alignment, nil
@colspan = options.fetch :colspan, 1
+ @width = options.fetch :width, @value.to_s.size
+ @index = options.fetch :index
+ @table = options.fetch :table
end
+ def alignment?
+ !@alignment.nil?
+ end
+
+ def alignment
+ @alignment || :left
+ end
+
+ def alignment=(val)
+ supported = %w(left center right)
+ if supported.include?(val.to_s)
+ @alignment = val
+ else
+ raise "Aligment must be one of: #{supported.join(' ')}"
+ end
+ end
+
+ def lines
+ @value.to_s.split(/\n/)
+ end
+
##
# Render the cell.
- def render
- " #{value} ".align alignment, width + 2
+ def render(line = 0)
+ left = " " * @table.style.padding_left
+ right = " " * @table.style.padding_right
+ "#{left}#{lines[line]}#{right}".align(alignment, width + @table.cell_padding)
end
alias :to_s :render
##
- # Cell length.
+ # Returns the longest line in the cell and
+ # removes all ANSI escape sequences (e.g. color)
- def length
- value.to_s.length + 2
+ def value_for_column_width_recalc
+ str = lines.sort_by { |s| s.size }.last.to_s
+ str = str.gsub(/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/, '')
+ str = str.gsub(/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/, '')
+ str.gsub(/[\x03|\x1a]/, '')
+ end
+
+ ##
+ # Returns the width of this cell
+
+ def width
+ padding = (colspan - 1) * @table.cell_spacing
+ inner_width = (1..@colspan).to_a.inject(0) do |w, counter|
+ w + @table.column_width(@index + counter - 1)
+ end
+ inner_width + padding
end
end
end
end
\ No newline at end of file