Class: Tabmani::Table

Inherits:
Tefil::TextFilterBase
  • Object
show all
Defined in:
lib/tabmani/table.rb

Defined Under Namespace

Classes: DuplicateCellError, ParseError, SymbolMismatchError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(matrix:, indent: 0) ⇒ Table

Returns a new instance of Table.



17
18
19
20
21
22
# File 'lib/tabmani/table.rb', line 17

def initialize(matrix: , indent: 0)
  @matrix = matrix
  @titles = nil
  @indent = indent
  @hlines = []
end

Instance Attribute Details

#indentObject (readonly)

Returns the value of attribute indent.



11
12
13
# File 'lib/tabmani/table.rb', line 11

def indent
  @indent
end

#matrixObject (readonly)

Returns the value of attribute matrix.



11
12
13
# File 'lib/tabmani/table.rb', line 11

def matrix
  @matrix
end

#titlesObject (readonly)

Returns the value of attribute titles.



11
12
13
# File 'lib/tabmani/table.rb', line 11

def titles
  @titles
end

Class Method Details

.dump_column_format(matrix:, hlines: [], io: $stdout, indent: 0, titles: nil, just: :left, separator: ' ') ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/tabmani/table.rb', line 74

def self.dump_column_format(matrix:,
                            hlines: [],
                            io: $stdout,
                            indent: 0,
                            titles: nil,
                            just: :left,
                            separator: ' ')
  matrix = [titles, * matrix] if titles
  maxima =  self.max_lengths(matrix)
  lines = matrix.map do |row|
    self.line_str(items: row,
                  lengths: maxima,
                  separator: separator,
                  just: just,
                  indent: indent)
  end
  hlines.sort.reverse.each { |index| lines.insert(index, '-' * whole_length(matrix)) }
  io.puts lines.join("\n")
end

.get_ranges(ary) ⇒ Object

true の範囲を示す二重配列を返す。各要素は 始点..終点 の各インデックスで出来た範囲。各要素は[始点, 終点] の各インデックス。



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/tabmani/table.rb', line 101

def self.get_ranges(ary)
  results = []
  start = nil
  prev = false
  ary << false # for true in final item
  ary.each_with_index do |cur, i|
    if prev == false && cur == true
      start = i
      prev = cur
    elsif prev == true && cur == false
      results << (start..(i - 1))
      prev = cur
    else
      next
    end
  end
  ary.pop
  results
end

.line_str(items:, lengths:, lineend: nil, just: :left, indent: 0, separator: ' ') ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/tabmani/table.rb', line 165

def self.line_str(items: ,
                  lengths: ,
                  lineend: nil,
                  just: :left,
                  indent: 0,
                  separator: ' ')

  new_items = []
  lengths.each_with_index do |length, index|
    item = items[index].to_s
    new_items[index] = self.padding(str: item, width: lengths[index], place: just)
  end
  str = " " * indent
  str += new_items.join(separator)
  if lineend
    str += lineend
  else
    str.sub!(/ +$/, "")
  end
  str
end

.max_lengths(matrix) ⇒ Object

return array of max size of item at index



188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/tabmani/table.rb', line 188

def self.max_lengths(matrix)
  results = []
  matrix.each do |row|
    row.each_with_index do |item, index|
      item = item.to_s
      results[index] ||= 0
      size = Tabmani::Table.print_size(item)
      results[index] = size if results[index] < size
    end
  end
  results
end

.num_columns(matrix) ⇒ Object



161
162
163
# File 'lib/tabmani/table.rb', line 161

def self.num_columns(matrix)
  matrix.map{|items| items.size}.max
end

.padding(str:, width:, padding: ' ', place: :left) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/tabmani/table.rb', line 141

def self.padding(str: , width: , padding: ' ', place: :left)
  output_width = str.each_char.map{|c| c.bytesize == 1 ? 1 : 2}.reduce(0, &:+)
  padding_size = [0, width - output_width].max

  case place
  when :left   ; left = 0                ; right = padding_size
  when :right  ; left = padding_size     ; right = 0
  when :center ; left = padding_size / 2 ; right = padding_size - left
  else
    raise SymbolMismatchError, place
  end
  (padding * left) + str + (padding * right)
end

.parse(io:, style:, separator: ',') ⇒ Object

Wrapper for various parse method. style: :csv, :blank, or :column separator: option for separator style



27
28
29
30
31
32
33
34
35
36
# File 'lib/tabmani/table.rb', line 27

def self.parse(io: , style: , separator: ',')
  case style
  when :csv    ; self.parse_csv(io)
  when :blank  ; self.parse_blanks_separated_value(io)
  when :column ; self.parse_column_based_value(io)
  when :separator ; self.parse_separator(io, separator)
  else;
    raise ParseError, "Unknown style: #{style}"
  end
end

.parse_blanks_separated_value(io) ⇒ Object

blanks_separated_value



51
52
53
54
55
56
57
58
59
# File 'lib/tabmani/table.rb', line 51

def self.parse_blanks_separated_value(io)
  lines = io.readlines
  indent = lines.map{|line| /^(\s*)/ =~ line; $1.length}.min
  matrix = lines.map { |line| line.strip.split(/\s+/) }

  lines.map { |line| line.strip.split(/\s+/) }

  self.new(matrix: matrix, indent: indent)
end

.parse_column_based_value(io) ⇒ Object

column_based_value 縦に貫通する空白列を区切りにする。各要素の空白は strip する。



64
65
66
67
68
69
70
71
72
# File 'lib/tabmani/table.rb', line 64

def self.parse_column_based_value(io)
  lines = io.readlines
  return if lines.empty?
  lines.map!      { |line| line.chomp  }
  lines.delete_if { |line| line.empty? } # delete line consist of linefeed only.
  ranges = self.get_ranges(self.projection_ary(lines))
  matrix = lines.map { |line| ranges.map { |range| line[range].to_s.strip} }
  self.new(matrix: matrix)
end

.parse_csv(io) ⇒ Object

CSV



39
40
41
# File 'lib/tabmani/table.rb', line 39

def self.parse_csv(io)
  self.new(matrix: CSV.parse(io))
end

.parse_separator(io, separator) ⇒ Object



43
44
45
46
47
48
# File 'lib/tabmani/table.rb', line 43

def self.parse_separator(io, separator)

  lines = io.readlines
  matrix = lines.map { |line| line.chomp.split(separator) }
  self.new(matrix: matrix)
end


94
95
96
# File 'lib/tabmani/table.rb', line 94

def self.print_size(string)
  string.each_char.map{|c| c.bytesize == 1 ? 1 : 2}.reduce(0, &:+)
end

.projection_ary(lines) ⇒ Object

全ての文字列の最大長を要素数とする配列で、空白文字以外があれば true, 全て空白文字ならば false にした配列。



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/tabmani/table.rb', line 123

def self.projection_ary(lines)
  return [] if lines.empty?
  max_length = lines.max_by{|line| line.size}.size
  results = Array.new(max_length).fill(false)
  lines.each do |line|
    line.chomp.size.times do |i|
      c = line[i]
      next if results[i] == true
      if c == ' '
        next
      else
        results[i] = true
      end
    end
  end
  results
end

.whole_length(matrix) ⇒ Object



155
156
157
158
159
# File 'lib/tabmani/table.rb', line 155

def self.whole_length(matrix)
  result = 0
  self.max_lengths(matrix).each { |l| result += l}
  result += num_columns(matrix) - 1
end

Instance Method Details

#add_hline(num) ⇒ Object

num is the index of row number below the horizontal line.



419
420
421
# File 'lib/tabmani/table.rb', line 419

def add_hline(num)
  @hlines << num
end

#add_sum(key) ⇒ Object



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/tabmani/table.rb', line 401

def add_sum(key)
  index = key.to_i - 1
  sum = 0
  @matrix.each do |items|
    str = items[index]
    if str.include?('.')
      sum += str.to_f
    else
      sum += str.to_i
    end
  end
  items = Array.new(num_columns).fill('')
  items[index] = sum.to_s
  add_hline( @matrix.size)
  @matrix << items
end

#analyze(io:, keys:) ⇒ Object



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/tabmani/table.rb', line 364

def analyze(io: , keys:)
  io.puts

  unless @titles
    @titles = []
    num_columns.times do |i|
      @titles[i] = @matrix[0][i].to_s
    end
  end

  if @matrix.size != 0
    results = []
    results << %w(key head types)
    @titles.size.times do |i|
      results << [(i+1).to_s, @titles[i].strip,
        @matrix.map {|items| items[i]}.sort_by{|j| j.to_s}.uniq.size.to_s
      ]
    end
    Tabmani::Table.dump_column_format(matrix: results, io: io)
  end

  unless keys.empty?
    io.puts
    io.puts "key analysis"
    keys.each do |key|
      io.puts "(key=#{key})"
      values = @matrix.map{|items| items[key.to_i-1] }
      names = values.sort.uniq
      results = []
      names.each { |name| results << [name, values.count(name).to_s] }
      results.sort_by!{|v| v[1].to_i}
      Tabmani::Table.dump_column_format(matrix: results, io: io)
      io.puts
    end
  end
end

#dump(io:, style:, just: :left, separator: ' ') ⇒ Object

Wrapper for various dump method.



202
203
204
205
206
207
208
209
210
211
# File 'lib/tabmani/table.rb', line 202

def dump(io: , style: , just: :left, separator: ' ')
  case style
  when :column ; dump_column_format(io: io, just: just, separator: separator )
  when :csv    ; dump_csv(io: io)
  when :mds    ; dump_md_simple(io: io, just: just )
  when :tex    ; dump_tex(io: io, just: just )
  else
    raise ParseError, "Unknown style: #{style}"
  end
end

#dump_column_format(io: $stdout, just: :left, separator: ' ') ⇒ Object



213
214
215
216
217
218
219
220
221
# File 'lib/tabmani/table.rb', line 213

def dump_column_format(io: $stdout, just: :left, separator: ' ')
  self.class.dump_column_format(matrix: @matrix,
                                hlines: @hlines,
                                titles: @titles,
                                io: io,
                                indent: @indent,
                                just: just,
                                separator: separator)
end

#dump_csv(io:) ⇒ Object



223
224
225
226
227
228
229
230
# File 'lib/tabmani/table.rb', line 223

def dump_csv(io: )
  matrix = @matrix
  matrix = [@titles, * @matrix] if @titles
  csv_string = CSV.generate do |csv|
    matrix.each { |items| csv << items }
  end
  io.print csv_string
end

#dump_md_simple(io: $stdout, just: :left) ⇒ Object

markdown simple table style



233
234
235
236
237
238
239
240
241
# File 'lib/tabmani/table.rb', line 233

def dump_md_simple(io: $stdout, just: :left)
  if @titles
    matrix = [@titles, * @matrix] if @titles
  else
    matrix = @matrix.clone
  end
  matrix.insert(1, line_row)
  self.class.dump_column_format(io: io, matrix: matrix, just: just)
end

#dump_tex(io: $stdout, just: :left) ⇒ Object



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
# File 'lib/tabmani/table.rb', line 243

def dump_tex(io: $stdout, just: :left)
  case just
  when :left   ; just_char = 'l'
  when :right  ; just_char = 'r'
  when :center ; just_char = 'c'
  end

  maxima = max_lengths
  h_size = @matrix.map{|row| row.size }.max

  io.puts "\\begin{tabular}{#{just_char * h_size }}"

  lines = []
  if @titles
    lines << self.class.line_str(items: @titles,
                  lengths: maxima,
                  separator: " & ",
                  just: just,
                  lineend: ' \\\\',
                  indent: 2)
    @hlines << 1
  end

  @matrix.each do |row|
    lines << self.class.line_str(items: row,
                  lengths: maxima,
                  separator: " & ",
                  just: just,
                  lineend: ' \\\\',
                  indent: 2)
  end
  #@hlines = [0, maxima.size] if @hlines.empty?
  @hlines << 0
  @hlines << maxima.size
  @hlines.sort.reverse.each do |index|
    lines.insert(index, "  \\hline")
  end
  io.puts lines.join("\n")
  io.puts "\\end{tabular}"
end

#filter(key, val) ⇒ Object



317
318
319
320
321
# File 'lib/tabmani/table.rb', line 317

def filter(key, val)
  result = Marshal.load(Marshal.dump(self))
  result.filter!(key, val)
  result
end

#filter!(key, val) ⇒ Object



311
312
313
314
315
# File 'lib/tabmani/table.rb', line 311

def filter!(key, val)
  @matrix.select! do |items|
    items[key.to_i - 1] == val
  end
end

#max_lengthsObject

return array of max size of item at index



357
358
359
360
361
# File 'lib/tabmani/table.rb', line 357

def max_lengths
  matrix = @matrix
  matrix = [@titles, * @matrix] if @titles
  self.class.max_lengths(matrix)
end

#reform(key_x, key_y, key_val) ⇒ Object



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/tabmani/table.rb', line 323

def reform(key_x, key_y, key_val)
  x_index = key_x  .to_i - 1
  y_index = key_y  .to_i - 1
  v_index = key_val.to_i - 1

  data_hash = {}
  xs = []
  ys = []
  @matrix.each do |items|
    next if items.empty?
    x = items[x_index]
    y = items[y_index]
    v = items[v_index]
    data_hash[y] ||= {}
    raise DuplicateCellError, "Duplicated condition: #{x}, #{y}" if data_hash[y][x]
    data_hash[y][x] = v
    xs << x
    ys << y
  end

  xs = xs.sort.uniq
  ys = ys.sort.uniq
  matrix = []
  matrix << [''] + xs
  ys.each do |y|
    items = []
    items << y
    xs.each { |x| items << data_hash[y][x] }
    matrix << items
  end
  @matrix = matrix
end

#set_titleObject



430
431
432
# File 'lib/tabmani/table.rb', line 430

def set_title
  @titles = @matrix.shift
end

#show_keys(io: $stdout, separator: ' ') ⇒ Object



284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/tabmani/table.rb', line 284

def show_keys(io: $stdout, separator: ' ')
  matrix = []
  matrix << line_row

  tmp = []
  max_lengths.size.times do |i|
    tmp << (i + 1).to_s
  end
  matrix << tmp

  self.class.dump_column_format(matrix: matrix, io: io, indent: @indent)
end

#stripObject

delete spaces head or tail in each items. Destructive



424
425
426
427
428
# File 'lib/tabmani/table.rb', line 424

def strip
  @matrix.map! do |items|
    items.map {|str| str.strip}
  end
end

#transposeObject



305
306
307
308
309
# File 'lib/tabmani/table.rb', line 305

def transpose
  result = Marshal.load(Marshal.dump(self))
  result.transpose!
  result
end

#transpose!Object

transpose matrix. empty cell is filled by empty String, ”. thanks: www.tom08.net/entry/2017/12/21/125127



300
301
302
303
# File 'lib/tabmani/table.rb', line 300

def transpose!
  max_length = @matrix.max_by(&:size).size
  @matrix = @matrix.map { |m| m.fill('', m.size, max_length - m.size) }.transpose
end