19
20
21
22
23
24
25
26
27
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
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
|
# File 'lib/hansen_lab/tasks/align_columns.rb', line 19
def process(target, *filepaths)
tables = filepaths.collect do |filepath|
log_basename :align, filepath
parse_table(File.read(filepath))
end
sorting_keys = []
key_hashes = tables.collect do |table|
keys = case sort_column
when Integer then table.column(sort_column)
when String then table.column_by_header(sort_column)
end
hash = {}
keys.each_with_index do |key, i|
(hash[key] ||= []) << i
end
sorting_keys.concat(keys)
hash
end
sorting_keys = sorting_keys.uniq.sort.delete_if do |key|
key.strip.empty?
end
sorting_keys.each do |key|
max = key_hashes.inject(0) do |max, hash|
row_index = (hash[key] ||= [])
row_index.length > max ? row_index.length : max
end
key_hashes.each do |hash|
row_index = hash[key]
row_index.concat Array.new(max - row_index.length, nil)
end
end
prepare(target)
File.open(target, "wb") do |file|
= []
filepaths.each_with_index do |filepath, i|
table = tables[i]
unless table.n_columns == 0
array = table.blank_row
array[0] = "# #{File.basename(filepath)}"
<< array.join(col_sep)
end
end
file.print format_row()
if
row = tables.collect {|table| table..join(col_sep)}
file.print format_row(row)
end
sorting_keys.each do |key|
key_rows = []
tables.each_with_index do |table, index|
row_index = key_hashes[index][key]
rows = row_index.collect do |i|
(i == nil ? table.blank_row : table.data[i]).join(col_sep)
end
key_rows << rows
end
key_rows.transpose.collect do |row|
file.print format_row(row)
end
end
end
target
end
|