table-formatter 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/table-formatter.rb +45 -0
- metadata +55 -0
@@ -0,0 +1,45 @@
|
|
1
|
+
#!/usr/bin/ruby
|
2
|
+
|
3
|
+
class TableFormatter
|
4
|
+
|
5
|
+
attr_accessor :source, :labels
|
6
|
+
|
7
|
+
def initialize()
|
8
|
+
end
|
9
|
+
|
10
|
+
def display
|
11
|
+
a = @source
|
12
|
+
labels = @labels
|
13
|
+
column_widths = fetch_column_widths(a)
|
14
|
+
records = format_rows(a.clone, column_widths)
|
15
|
+
div = '-' * records[0].length + "\n"
|
16
|
+
label_buffer = ''
|
17
|
+
label_buffer = format_cols(labels, column_widths) + "\n" + div if labels
|
18
|
+
div + label_buffer + records.join("\n") + "\n" + div
|
19
|
+
end
|
20
|
+
|
21
|
+
private
|
22
|
+
|
23
|
+
def tabulate(a)
|
24
|
+
a[0].zip(a.length > 2 ? tabulate(a[1..-1]) : a[-1])
|
25
|
+
end
|
26
|
+
|
27
|
+
def fetch_column_widths(a)
|
28
|
+
d = tabulate(a).map &:flatten
|
29
|
+
|
30
|
+
# find the maximum lengths
|
31
|
+
d.map{|x| x.max_by(&:length).length}
|
32
|
+
end
|
33
|
+
|
34
|
+
def format_cols(row, col_widths)
|
35
|
+
buffer = '|'
|
36
|
+
row.each_with_index do |col, i|
|
37
|
+
buffer += ' ' + col.ljust(col_widths[i] + 2) + '|'
|
38
|
+
end
|
39
|
+
buffer
|
40
|
+
end
|
41
|
+
|
42
|
+
def format_rows(a, col_widths)
|
43
|
+
a.map {|row| format_cols(row, col_widths)}
|
44
|
+
end
|
45
|
+
end
|
metadata
ADDED
@@ -0,0 +1,55 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: table-formatter
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors: []
|
7
|
+
|
8
|
+
autorequire:
|
9
|
+
bindir: bin
|
10
|
+
cert_chain: []
|
11
|
+
|
12
|
+
date: 2010-05-02 00:00:00 +01:00
|
13
|
+
default_executable:
|
14
|
+
dependencies: []
|
15
|
+
|
16
|
+
description:
|
17
|
+
email:
|
18
|
+
executables: []
|
19
|
+
|
20
|
+
extensions: []
|
21
|
+
|
22
|
+
extra_rdoc_files: []
|
23
|
+
|
24
|
+
files:
|
25
|
+
- lib/table-formatter.rb
|
26
|
+
has_rdoc: true
|
27
|
+
homepage:
|
28
|
+
licenses: []
|
29
|
+
|
30
|
+
post_install_message:
|
31
|
+
rdoc_options: []
|
32
|
+
|
33
|
+
require_paths:
|
34
|
+
- lib
|
35
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
36
|
+
requirements:
|
37
|
+
- - ">="
|
38
|
+
- !ruby/object:Gem::Version
|
39
|
+
version: "0"
|
40
|
+
version:
|
41
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
42
|
+
requirements:
|
43
|
+
- - ">="
|
44
|
+
- !ruby/object:Gem::Version
|
45
|
+
version: "0"
|
46
|
+
version:
|
47
|
+
requirements: []
|
48
|
+
|
49
|
+
rubyforge_project:
|
50
|
+
rubygems_version: 1.3.5
|
51
|
+
signing_key:
|
52
|
+
specification_version: 3
|
53
|
+
summary: table-formatter prints a table in plain text format from an array
|
54
|
+
test_files: []
|
55
|
+
|