Permalink
Browse files

Add ability for table titles

  • Loading branch information...
1 parent fc33d82 commit 9e8940d328332ed0274d685d278f06129dda842c @rrrene rrrene committed Oct 17, 2011
Showing with 41 additions and 11 deletions.
  1. +1 −0 examples/examples.rb
  2. +21 −11 lib/terminal-table/table.rb
  3. +19 −0 spec/table_spec.rb
View
@@ -14,6 +14,7 @@
puts
user_table = table do |v|
+ v.title = "Contact Information"
v.headings = 'First Name', 'Last Name', 'Email'
v << %w( TJ Holowaychuk tj@vision-media.ca )
v << %w( Bob Someone bob@vision-media.ca )
@@ -13,6 +13,7 @@ class Table
X, Y, I = '-', '|', '+'
+ attr_reader :title
attr_reader :headings
attr_accessor :width
@@ -112,6 +113,11 @@ def headings= array
def render
@seperator = nil
buffer = [separator]
+ unless @title.nil?
+ opts = {:value => @title, :alignment => :center, :colspan => number_of_columns}
+ buffer << Row.new(self, [opts]).render
+ buffer << separator
+ end
unless @headings.empty?
buffer << @headings.render
buffer << separator
@@ -136,16 +142,6 @@ def rows= array
end
##
- # Check if _other_ is equal to self. _other_ is considered equal
- # if it contains the same headings and rows.
-
- def == other
- if other.respond_to? :render and other.respond_to? :rows
- self.headings == other.headings and self.rows == other.rows
- end
- end
-
- ##
# Create a separator based on colum lengths.
def separator
@@ -156,6 +152,21 @@ def separator
end
end
+ def title=(title)
+ @title = title
+ recalc_column_widths Row.new(self, [title])
+ end
+
+ ##
+ # Check if _other_ is equal to self. _other_ is considered equal
+ # if it contains the same headings and rows.
+
+ def == other
+ if other.respond_to? :render and other.respond_to? :rows
+ self.headings == other.headings and self.rows == other.rows
+ end
+ end
+
private
def columns_width
@@ -204,7 +215,6 @@ def headings_with_rows
[@headings] + rows
end
-
def yield_or_eval &block
return unless block
if block.arity > 0
View
@@ -132,6 +132,25 @@ module Terminal
EOF
end
+ it "should render title properly" do
+ @table.title = "Title"
+ @table.headings = ['Char', 'Num']
+ @table << ['a', 1]
+ @table << ['b', 2]
+ @table << ['c', 3]
+ @table.render.should == <<-EOF.deindent
+ +-------+-----+
+ | Title |
+ +-------+-----+
+ | Char | Num |
+ +-------+-----+
+ | a | 1 |
+ | b | 2 |
+ | c | 3 |
+ +-------+-----+
+ EOF
+ end
+
it "should render properly without headings" do
@table << ['a', 1]
@table << ['b', 2]

0 comments on commit 9e8940d

Please sign in to comment.