Class: Tabularize

Inherits:
Object
  • Object
show all
Defined in:
lib/tabularize.rb,
lib/tabularize/version.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :align        => :left,
  :valign       => :top,
  :pad          => ' ',
  :pad_left     => 0,
  :pad_right    => 0,

  :border_style => :ascii,
  :border_color => nil,

  :unicode      => true,
  :ansi         => true,

  :ellipsis     => '>',
  :screen_width => nil
}.freeze
DEFAULT_OPTIONS_GENERATOR =
{
  :pad_left  => 1,
  :pad_right => 1
}.freeze
BORDER_STYLE =
{
  :ascii => {
    :hborder      => '-',
    :vborder      => '|',
    :iborder      => %w[+ + + + + + + + +]
  },
  :unicode => {
    :hborder      => '',
    :vborder      => '',
    :iborder      => %w[        ]
  }
}.freeze
VERSION =
'0.3.0'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Tabularize

Returns a new instance of Tabularize.

Since:

  • 0.2.0



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/tabularize.rb', line 48

def initialize(options = {})
  @rows    = []
  @seps    = Hash.new { |h, k| h[k] = 0 }
  @options = DEFAULT_OPTIONS
             .merge(DEFAULT_OPTIONS_GENERATOR)
             .merge(options)
  if @options[:border_style]
    @options = BORDER_STYLE[@options[:border_style]].merge(@options)

    # Backward-compatibility
    unless @options[:iborder].is_a?(Array)
      @options[:iborder] = [@options[:iborder]] * 9
    end
  end
  @cache = {}
end

Class Method Details

.analyze(data, options = {}) ⇒ Object

Determines maximum widths of cells and maximum heights of rows



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/tabularize.rb', line 199

def self.analyze(data, options = {})
  unicode     = options[:unicode]
  ansi        = options[:ansi]
  max_widths  = (options[:max_widths] || []).dup
  max_heights = (options[:max_heights] || []).dup
  rows        = []

  data.each_with_index do |row, ridx|
    rows << row = [*row].map(&:to_s)

    row.each_with_index do |cell, idx|
      nlines = 0
      (cell.empty? ? [''] : cell.lines).each do |c|
        max_widths[idx] =
          [Tabularize.cell_width(c.chomp, unicode, ansi),
           max_widths[idx] || 0].max
        nlines += 1
      end
      max_heights[ridx] = [nlines, max_heights[ridx] || 1].max
    end
  end

  num_cells = max_widths.length
  rows.each do |row|
    [num_cells - row.length, 0].max.times do
      row << ''
    end
  end

  {
    :rows        => rows,
    :max_widths  => max_widths,
    :max_heights => max_heights
  }
end

.cell_width(str, unicode, ansi) ⇒ Integer

Returns the display width of a String

Parameters:

  • str (String)

    Input String

  • unicode (Boolean)

    Set to true when the given String can include CJK wide characters

  • ansi (Boolean)

    Set to true When the given String can include ANSI codes

Returns:

  • (Integer)

    Display width of the given String

Since:

  • 0.2.0



193
194
195
196
# File 'lib/tabularize.rb', line 193

def self.cell_width(str, unicode, ansi)
  str = str.gsub(/\e\[\d*(?:;\d+)*m/, '') if ansi
  unicode ? Unicode::DisplayWidth.of(str) : str.length
end

.it(table_data, options = {}) ⇒ Array

Formats two-dimensional tabular data. One-dimensional data (e.g. Array of Strings) is treated as tabular data of which each row has only one column.

Parameters:

  • table_data (Enumerable)
  • options (Hash) (defaults to: {})

    Formatting options.

Returns:

  • (Array)

    Two-dimensional Array of formatted cells.

Raises:

  • (ArgumentError)


241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/tabularize.rb', line 241

def self.it(table_data, options = {})
  raise ArgumentError, 'Not enumerable' unless
      table_data.respond_to?(:each)

  options = DEFAULT_OPTIONS.merge(options)
  pad     = options[:pad].to_s
  padl    = options[:pad_left]
  padr    = options[:pad_right]
  align   = [*options[:align]]
  valign  = [*options[:valign]]
  unicode = options[:unicode]
  ansi    = options[:ansi]
  screenw = options[:screen_width]

  raise ArgumentError, 'Invalid padding' unless pad.length == 1
  unless padl.is_a?(Integer) && padl >= 0
    raise ArgumentError, ':pad_left must be a non-negative integer'
  end
  unless padr.is_a?(Integer) && padr >= 0
    raise ArgumentError, ':pad_right must be a non-negative integer'
  end
  unless align.all? { |a| %i[left right center].include?(a) }
    raise ArgumentError, 'Invalid alignment'
  end
  unless valign.all? { |a| %i[top bottom middle].include?(a) }
    raise ArgumentError, 'Invalid vertical alignment'
  end
  unless screenw.nil? || (screenw.is_a?(Integer) && screenw > 0)
    raise ArgumentError, ':screen_width must be a positive integer'
  end

  # Analyze data
  ret = options[:analysis] || Tabularize.analyze(table_data, options)
  rows, max_widths, max_heights =
    %i[rows max_widths max_heights].map { |k| ret[k] }

  ridx = -1
  rows.map do |row|
    ridx += 1
    idx = -1
    max_height = max_heights[ridx]
    row.map do |cell|
      idx += 1
      lines = cell.to_s.lines.to_a
      offset =
        case valign[idx] || valign.last
        when :top
          0
        when :bottom
          max_height - lines.length
        when :middle
          (max_height - lines.length) / 2
        end

      (0...max_height).map do |ln|
        ln -= offset
        str = ln >= 0 && lines[ln] ? lines[ln].chomp : (pad * max_widths[idx])
        alen =
          if ansi
            Tabularize.cell_width(str, false, false) -
              Tabularize.cell_width(str, false, true)
          else
            0
          end
        slen = str.length - alen

        w = max_widths[idx]
        w += str.length - Unicode::DisplayWidth.of(str) if unicode
        pad * padl +
          case align[idx] || align.last
          when :left
            str.ljust(w + alen, pad)
          when :right
            str.rjust(w + alen, pad)
          when :center
            str.rjust((w - slen) / 2 + slen + alen, pad).ljust(w + alen, pad)
          end +
          pad * padr
      end.join($RS)
    end
  end
end

Instance Method Details

#<<(row) ⇒ Object

Parameters:

  • row (Array)

Since:

  • 0.2.0



73
74
75
76
# File 'lib/tabularize.rb', line 73

def <<(row)
  @rows << row
  nil
end

#separator!Object

Since:

  • 0.2.0



66
67
68
69
# File 'lib/tabularize.rb', line 66

def separator!
  @seps[@rows.length] += 1
  nil
end

#to_sString

Returns:

  • (String)

Since:

  • 0.2.0



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
# File 'lib/tabularize.rb', line 80

def to_s
  return nil if @rows.empty?

  # Invalidate cache if needed
  num_cached_rows = @cache[:num_rows] || 0
  analysis = Tabularize.analyze(
    @rows[num_cached_rows..-1], @options.merge(@cache[:analysis] || {})
  )

  unless @cache.empty?
    cmw = @cache[:analysis][:max_widths]
    mw  = analysis[:max_widths]
    if mw.zip(cmw).any? { |pair| pair.first > (pair.last || 0) }
      @cache = {}
      num_cached_rows = 0
    else
      [@seps[@rows.length] - @cache[:last_seps], 0].max.times do
        @cache[:string_io].puts @cache[:separators][1]
      end
      @cache[:last_seps] = @seps[@rows.length]

      if num_cached_rows == @rows.length
        return @cache[:string_io].string + @cache[:separators].last
      end
    end
  end

  rows = Tabularize.it(@rows[num_cached_rows..-1], @options.merge(analysis))

  h  = @options[:hborder]
  v  = @options[:vborder]
  vl = @options[:vborder]
  i9 = @options[:iborder]
  e  = @options[:ellipsis]
  c  = @options[:border_color] || ''
  r  = c.empty? ? '' : "\e[0m"
  u  = @options[:unicode]
  a  = @options[:ansi]
  sw = @options[:screen_width]
  el = Tabularize.cell_width(e, u, a)

  separators = @cache[:separators]
  col_count = @cache[:col_count]
  separators ||=
    Array.new(3) { '' }.zip(i9.each_slice(3).to_a).map do |separator, i3|
      rows[0].each_with_index do |ch, idx|
        new_sep = separator +
                  i3[idx.zero? ? 0 : 1] +
                  h * Tabularize.cell_width(ch, u, a)

        if sw && Tabularize.cell_width(new_sep, true, true) > sw - el
          col_count = idx
          break
        else
          separator = new_sep
        end
      end
      separator += col_count ? e : i3.last
      if c
        c + separator + r
      else
        separator
      end
    end

  output = @cache[:string_io] || StringIO.new.tap do |io|
    io.set_encoding 'UTF-8' if io.respond_to? :set_encoding
    io.puts separators.first
  end
  if col_count
    rows = rows.map { |line| line[0, col_count] }
    vl = e
  end
  rows.each_with_index do |row, idx|
    row = row.map { |val| val.lines.to_a.map(&:chomp) }
    height = row[0] ? row[0].count : 1
    @seps[idx + num_cached_rows].times do
      output.puts separators[1]
    end
    (0...height).each do |line|
      output.print c + v + r unless row.empty?
      output.puts row.map { |lines|
        lines[line] || @options[:pad] * Tabularize.cell_width(lines[0], u, a)
      }.join(c + v + r) + c + vl + r
    end
  end

  @seps[rows.length + num_cached_rows].times do
    output.puts separators[1]
  end

  @cache = {
    :analysis   => analysis,
    :separators => separators,
    :col_count  => col_count,
    :num_rows   => @rows.length,
    :string_io  => output,
    :last_seps  => @seps[rows.length]
  }
  output.string + separators.last
rescue StandardError
  @cache = {}
  raise
end