Module: Ghostwriter::Writer::TableWriter

Included in:
Ghostwriter::Writer
Defined in:
lib/ghostwriter/writer.rb

Overview

Methods for processing tables

Instance Method Summary collapse

Instance Method Details

#add_table_header_underline(table, column_sizes) ⇒ Object



179
180
181
182
183
184
185
186
# File 'lib/ghostwriter/writer.rb', line 179

def add_table_header_underline(table, column_sizes)
   table.search('./thead').each do |thead|
      lines         = column_sizes.collect { |len| @table_row * (len + 2) }
      underline_row = "#{ table_corner }#{ lines.join(@table_corner) }#{ @table_corner }"

      thead.replace("#{ thead.inner_html }#{ underline_row }\n")
   end
end

#calculate_column_sizes(table) ⇒ Object



169
170
171
172
173
174
175
176
177
# File 'lib/ghostwriter/writer.rb', line 169

def calculate_column_sizes(table)
   column_sizes = table.search('tr').collect do |row|
      row.search('th', 'td').collect do |node|
         node.text.length
      end
   end

   column_sizes.transpose.collect(&:max)
end

#replace_table_nodes(row, column_sizes) ⇒ Object



188
189
190
191
192
193
194
# File 'lib/ghostwriter/writer.rb', line 188

def replace_table_nodes(row, column_sizes)
   row.search('th', 'td').each_with_index do |node, i|
      new_content = node.text.ljust(column_sizes[i] + 1)

      node.replace("#{ @table_column } #{ new_content }")
   end
end

#replace_tables(doc) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/ghostwriter/writer.rb', line 150

def replace_tables(doc)
   doc.css('table').each do |table|
      # remove whitespace between nodes
      table.search('//text()[normalize-space()=""]').remove

      column_sizes = calculate_column_sizes(table)

      table.search('./thead/tr', './tbody/tr', './tr').each do |row|
         replace_table_nodes(row, column_sizes)

         row.replace("#{ row.inner_html }#{ @table_column }\n")
      end

      add_table_header_underline(table, column_sizes)

      table.replace("\n#{ table.inner_html }\n")
   end
end