Class: Marktable::Formatters::Markdown
- Inherits:
-
Object
- Object
- Marktable::Formatters::Markdown
- Defined in:
- lib/marktable/formatters/markdown.rb
Class Method Summary collapse
- .calculate_column_widths(rows, headers) ⇒ Object
- .format(rows, headers = nil) ⇒ Object
- .separator_row(widths) ⇒ Object
Class Method Details
.calculate_column_widths(rows, headers) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/marktable/formatters/markdown.rb', line 28 def self.calculate_column_widths(rows, headers) # Determine the maximum number of columns to consider max_cols = headers ? headers.size : 0 if headers.nil? # Without headers, find the maximum number of values across all rows rows.each do |row| max_cols = [max_cols, row.values.size].max end end # Initialize widths array with zeros widths = Array.new(max_cols, 0) # Process headers if available headers&.each_with_index do |header, i| width = header.to_s.length widths[i] = width if width > widths[i] end # Process row values, but only up to the max_cols rows.each do |row| values = row.values.take(max_cols) values.each_with_index do |value, i| width = value.to_s.length widths[i] = width if width > widths[i] end end widths end |
.format(rows, headers = nil) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/marktable/formatters/markdown.rb', line 6 def self.format(rows, headers = nil) return '' if rows.empty? && headers.nil? # Calculate column widths widths = calculate_column_widths(rows, headers) lines = [] # Add header row if we have headers if headers lines << Row.new(headers).to_markdown(widths) lines << separator_row(widths) end # Add data rows rows.each do |row| lines << row.to_markdown(widths) end lines.join("\n") end |
.separator_row(widths) ⇒ Object
60 61 62 63 |
# File 'lib/marktable/formatters/markdown.rb', line 60 def self.separator_row(widths) separator_parts = widths.map { |width| '-' * width } "| #{separator_parts.join(' | ')} |" end |