Class: RenderAsMarkdown::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/render-as-markdown/table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(column_titles) ⇒ Table

Returns a new instance of Table.



6
7
8
9
10
# File 'lib/render-as-markdown/table.rb', line 6

def initialize column_titles
  # column_titles will be an array
  @columns = [*column_titles].map{|title| Column.new title}
  @rows = []
end

Instance Attribute Details

#columnsObject

Returns the value of attribute columns.



4
5
6
# File 'lib/render-as-markdown/table.rb', line 4

def columns
  @columns
end

#rowsObject

Returns the value of attribute rows.



4
5
6
# File 'lib/render-as-markdown/table.rb', line 4

def rows
  @rows
end

Instance Method Details

#add_row(row) ⇒ Object Also known as: <<



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/render-as-markdown/table.rb', line 12

def add_row row
  # TODO: ensure element count of row is == element count of columns

  # make row an array
  row = [*row]

  # add row to rows, use an array
  @rows << row

  # iterate through columns and row, add each row to their column
  @columns.zip(row).each {|col, val| col.add_row val.to_s}
end

#renderObject Also known as: to_s



28
29
30
# File 'lib/render-as-markdown/table.rb', line 28

def render
  render_head << render_seperator << render_body
end

#render_bodyObject



44
45
46
47
48
49
50
51
# File 'lib/render-as-markdown/table.rb', line 44

def render_body
  # join all columns for all rows
  body =''
  @rows.each_with_index do |row, i|
    body << render_row( i )
  end
  body
end

#render_headObject



34
35
36
37
# File 'lib/render-as-markdown/table.rb', line 34

def render_head
  # join all column headers
  @columns.map(&:render_title).join( '|' ) << "\n"
end

#render_row(row) ⇒ Object



53
54
55
# File 'lib/render-as-markdown/table.rb', line 53

def render_row row
  @columns.map {|col| col.render_row row}.join( '|' ) << "\n"
end

#render_seperatorObject



39
40
41
42
# File 'lib/render-as-markdown/table.rb', line 39

def render_seperator
  # join all column lines
  @columns.map(&:render_line).join( '|' ) << "\n"
end