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,

  :hborder   => '-',
  :vborder   => '|',
  :iborder   => '+',

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

  :ellipsis     => '>',
  :screen_width => nil,
}
DEFAULT_OPTIONS_GENERATOR =
{
  :pad_left  => 1,
  :pad_right => 1,
}
VERSION =
"0.2.5"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Tabularize

Returns a new instance of Tabularize.

Since:

  • 0.2.0



30
31
32
33
34
35
36
37
# File 'lib/tabularize.rb', line 30

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

Class Method Details

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

Determines maximum widths of cells and maximum heights of rows



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
# File 'lib/tabularize.rb', line 157

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.lines 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) ⇒ Fixnum

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:

  • (Fixnum)

    Display width of the given String

Since:

  • 0.2.0



151
152
153
154
# File 'lib/tabularize.rb', line 151

def self.cell_width str, unicode, ansi
  str = str.gsub(/\e\[\d*(?:;\d+)*m/, '') if ansi
  str.send(unicode ? :display_width : :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)


197
198
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
234
235
236
237
238
239
240
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
# File 'lib/tabularize.rb', line 197

def self.it table_data, options = {}
  raise ArgumentError.new("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]

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

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

  ridx = -1
  rows.map { |row| 
    ridx += 1
    idx = -1
    max_height = max_heights[ridx]
    row.map { |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 { |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 - str.display_width 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
      }.join($/)
    }
  }
end

Instance Method Details

#<<(row) ⇒ Object

Parameters:

  • row (Array)

Since:

  • 0.2.0



47
48
49
50
# File 'lib/tabularize.rb', line 47

def << row
  @rows << row
  nil
end

#separator!Object

Since:

  • 0.2.0



40
41
42
43
# File 'lib/tabularize.rb', line 40

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

#to_sString

Returns:

  • (String)

Since:

  • 0.2.0



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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
# File 'lib/tabularize.rb', line 54

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[:separator]
      end
      @cache[:last_seps] = @seps[@rows.length]

      if num_cached_rows == @rows.length
        return @cache[:string_io].string + @cache[:separator]
      end
    end
  end
  
  rows = Tabularize.it(@rows[num_cached_rows..-1], @options.merge(analysis))

  h  = @options[:hborder]
  v  = @options[:vborder]
  i  = @options[:iborder]
  vl = @options[:vborder]
  il = @options[:iborder]
  u  = @options[:unicode]
  a  = @options[:ansi]
  sw = @options[:screen_width]
  el = Tabularize.cell_width(@options[:ellipsis], u, a)

  separator = @cache[:separator]
  col_count = @cache[:col_count]
  unless separator
    separator = ''
    rows[0].each_with_index do |c, idx|
      new_sep = separator + i + h * Tabularize.cell_width(c, u, a)

      if sw && Tabularize.cell_width(new_sep, u, a) > sw - el
        col_count = idx
        break
      else
        separator = new_sep
      end
    end
    separator += il
  end

  output = @cache[:string_io] || StringIO.new.tap { |io| io.puts separator }
  if col_count
    rows = rows.map { |line| line[0, col_count] }
    vl = il = @options[:ellipsis]
  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 separator
    end
    (0...height).each do |line|
      output.print v unless row.empty?
      output.puts row.map { |lines|
        lines[line] || @options[:pad] * Tabularize.cell_width(lines[0], u, a)
      }.join(v) + vl
    end
  end

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

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