Class: RandomWords::TableCleanup

Inherits:
Object
  • Object
show all
Defined in:
lib/random-words/table-cleanup.rb

Overview

Table formatting, cleans up tables in content

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content = nil, options = nil) ⇒ TableCleanup

Initialize a table cleaner

Parameters:

  • content (String) (defaults to: nil)

    The content to clean

  • options (Hash) (defaults to: nil)

    The options



20
21
22
23
24
# File 'lib/random-words/table-cleanup.rb', line 20

def initialize(content = nil, options = nil)
  @content = content || ''
  @max_cell_width = options && options[:max_cell_width] ? options[:max_cell_width] : 30
  @max_table_width = options && options[:max_table_width] ? options[:max_table_width] : nil
end

Instance Attribute Details

#content=(value) ⇒ Object (writeonly)

The content to process



12
13
14
# File 'lib/random-words/table-cleanup.rb', line 12

def content=(value)
  @content = value
end

#max_cell_width=(value) ⇒ Object (writeonly)

Max cell width for formatting, defaults to 30



8
9
10
# File 'lib/random-words/table-cleanup.rb', line 8

def max_cell_width=(value)
  @max_cell_width = value
end

#max_table_width=(value) ⇒ Object (writeonly)

Max table width for formatting, defaults to 60



10
11
12
# File 'lib/random-words/table-cleanup.rb', line 10

def max_table_width=(value)
  @max_table_width = value
end

Instance Method Details

#align(alignment, string, width) ⇒ String

Align content withing cell based on header alignments

Parameters:

  • string (String)

    The string to align

  • width (Integer)

    The cell width

Returns:



80
81
82
83
84
85
86
87
88
89
# File 'lib/random-words/table-cleanup.rb', line 80

def align(alignment, string, width)
  case alignment
  when :left
    string.ljust(width, ' ')
  when :right
    string.rjust(width, ' ')
  when :center
    string.center(width, ' ')
  end
end

#build_table(table) ⇒ String

Builds a formatted table

Parameters:

  • table (Array<Array>)

    The table, an array of row arrays

Returns:

  • (String)

    the formatted table



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/random-words/table-cleanup.rb', line 44

def build_table(table)
  @widths = [0] * table.first.size

  table.each do |row|
    next unless row

    row.each_with_index do |cell, col|
      if @widths[col]
        @widths[col] = cell.size if @widths[col] < cell.size
      else
        @widths[col] = cell.size
      end
    end
  end

  @string = String.new

  first_row = table.shift
  render_row first_row
  render_alignment

  table.each do |row|
    render_row row
  end

  @string
end

#cleanObject

Clean tables within content



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/random-words/table-cleanup.rb', line 156

def clean
  table_rx = /^(?ix)(?<table>
  (?<header>\|?(?:.*?\|)+.*?)\s*\n
  ((?<align>\|?(?:[:-]+\|)+[:-]*)\s*\n)?
  (?<rows>(?:\|?(?:.*?\|)+.*?(?:\n|\Z))+))/

  @content = @content.gsub(/(\|?(?:.+?\|)+)\n\|\n/) do
    m = Regexp.last_match
    cells = parse_cells(m[1]).count
    "#{m[1]}\n#{'|' * cells}\n"
  end

  tables = @content.to_enum(:scan, table_rx).map { Regexp.last_match }

  tables.each do |t|
    table = []

    if t['align'].nil?
      cells = parse_cells(t['header'])
      align = "|#{([':---'] * cells.count).join('|')}|"
    else
      align = t['align']
    end

    next unless parse_cells(align.ensure_pipes)

    @alignment = parse_cells(align.ensure_pipes).map do |cell|
      if cell[0, 1] == ':' && cell[-1, 1] == ':'
        :center
      elsif cell[-1, 1] == ':'
        :right
      else
        :left
      end
    end

    lines = t['table'].split("\n")
    lines.delete_if(&:alignment?)

    lines.each do |row|
      # Ensure leading and trailing pipes
      row = row.ensure_pipes

      cells = parse_cells(row)

      table << cells
    end

    @content.sub!(/#{Regexp.escape(t['table'])}/, "#{build_table(table)}\n")
  end

  @content
end

#parse_cells(row) ⇒ Array

Split a row string on pipes

Parameters:

  • row (String)

    The row string

Returns:

  • (Array)

    array of cell strings



33
34
35
# File 'lib/random-words/table-cleanup.rb', line 33

def parse_cells(row)
  row.split('|').map(&:strip)[1..-1]
end

#render_alignmentObject

Render the alignment row



121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/random-words/table-cleanup.rb', line 121

def render_alignment
  @string << '|'
  return unless @alignment

  @alignment.zip(@widths).each do |align, width|
    @string << ':' if align == :left
    width = @max_cell_width - 2 if width >= @max_cell_width
    @string << ('-' * (width + (align == :center ? 2 : 1)))
    @string << ':' if align == :right
    @string << '|'
  end
  @string << "\n"
end

#render_row(row) ⇒ String

Render a row

Parameters:

  • row (Array)

    The row of cell contents

Returns:

  • (String)

    the formatted row



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/random-words/table-cleanup.rb', line 98

def render_row(row)
  idx = 0
  @max_cell_width = @max_table_width / row.count if @max_table_width

  return unless row

  @string << '|'
  row.zip(@widths).each do |cell, width|
    width = @max_cell_width - 2 if width >= @max_cell_width
    if width.zero?
      @string << '|'
    else
      content = @alignment ? align(@alignment[idx], cell, width) : cell.ljust(width, ' ')
      @string << " #{content} |"
    end
    idx += 1
  end
  @string << "\n"
end