From 306107e816c56e5f3f828b3218bde4a38adb20ca Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Thu, 15 Jan 2009 22:57:56 -0800 Subject: [PATCH] - Moved yield or eval to Termina::Table#initialize where it belongs - Added specs for instance eval syntax - Added specs for block syntax --- examples/examples.rb | 1 + lib/terminal-table/import.rb | 4 +--- lib/terminal-table/table.rb | 19 +++++++++++++++---- spec/table_spec.rb | 30 ++++++++++++++++++++++++++++++ 4 files changed, 47 insertions(+), 7 deletions(-) diff --git a/examples/examples.rb b/examples/examples.rb index ee32b5b..678f002 100644 --- a/examples/examples.rb +++ b/examples/examples.rb @@ -54,3 +54,4 @@ rows << [nil, ':)', nil] rows << [nil, nil, nil] puts table(nil, rows) + diff --git a/lib/terminal-table/import.rb b/lib/terminal-table/import.rb index c80e996..da7be69 100644 --- a/lib/terminal-table/import.rb +++ b/lib/terminal-table/import.rb @@ -48,8 +48,6 @@ module Kernel # def table headings = [], rows = [], &block - table = Terminal::Table.new :headings => headings, :rows => rows - table.yield_or_eval &block - table + table = Terminal::Table.new :headings => headings, :rows => rows, &block end end \ No newline at end of file diff --git a/lib/terminal-table/table.rb b/lib/terminal-table/table.rb index b2c615d..7399e78 100644 --- a/lib/terminal-table/table.rb +++ b/lib/terminal-table/table.rb @@ -29,6 +29,12 @@ module Terminal class Table + #-- + # Exceptions + #++ + + class Error < StandardError; end + ## # Table characters, x axis, y axis, and intersection. @@ -39,9 +45,10 @@ class Table ## # Generates a ASCII table. - def initialize options = {} + def initialize options = {}, &block @headings = options.delete(:headings) || [] - @rows = options.delete(:rows) || [] + @rows = options.delete(:rows) || [] + yield_or_eval &block if block_given? end ## @@ -118,8 +125,12 @@ def length_of_column n ## # Return total number of columns available. - def number_of_columns - rows[0].length + def number_of_columns + if rows[0] + rows[0].length + else + raise Error, 'Your table needs some rows' + end end ## diff --git a/spec/table_spec.rb b/spec/table_spec.rb index 2184fd1..22add65 100644 --- a/spec/table_spec.rb +++ b/spec/table_spec.rb @@ -89,6 +89,36 @@ EOF end + it "should render properly using block syntax" do + table = Terminal::Table.new do |t| + t << ['a', 1] + t << ['b', 2] + t << ['c', 3] + end + table.render.should == <<-EOF.deindent + +---+---+ + | a | 1 | + | b | 2 | + | c | 3 | + +---+---+ + EOF + end + + it "should render properly using instance_eval block syntax" do + table = Terminal::Table.new do + add_row ['a', 1] + add_row ['b', 2] + add_row ['c', 3] + end + table.render.should == <<-EOF.deindent + +---+---+ + | a | 1 | + | b | 2 | + | c | 3 | + +---+---+ + EOF + end + it "should allows a hash of options for creation" do headings = ['Char', 'Num'] rows = [['a', 1], ['b', 2], ['c', 3]]