table_print 1.5.7 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  Feature: Configuring output
2
+ @todo
2
3
  Scenario: Setting a (max? or specific?) width for all columns
3
4
  Scenario: Setting a specific width for an individual column
4
5
  Given a class named Blog
@@ -84,6 +85,7 @@ Feature: Configuring output
84
85
  ------|--------|-------
85
86
  post! | Ryan | post!
86
87
  """
88
+ @todo
87
89
  Scenario: Applying a formatter
88
90
  Scenario: Setting a column name
89
91
  Given a class named Blog
@@ -114,6 +116,63 @@ Feature: Configuring output
114
116
  Ryan
115
117
  """
116
118
 
119
+ Scenario: Setting the value for unreachable cells
120
+ Given a class named Blog
121
+
122
+ Given Blog has attributes title
123
+
124
+ When I instantiate a Blog with {:title => "post!"}
125
+ And I configure unreachable_value with 'unreachable'
126
+ And table_print Blog, [:title, :author]
127
+ Then the output should contain
128
+ """
129
+ TITLE | AUTHOR
130
+ ------|------------
131
+ post! | unreachable
132
+ """
133
+
134
+ Scenario: Removing the headers
135
+ Given a class named Blog
136
+
137
+ Given Blog has attributes title, author
138
+
139
+ When I instantiate a Blog with {:title => "post!", :author => 'Ryan'}
140
+ And I configure show_headers with false
141
+ And table_print Blog
142
+ Then the output should contain
143
+ """
144
+ post! | Ryan
145
+ """
146
+
147
+ Scenario: Setting the horizontal separator character
148
+ Given a class named Blog
149
+
150
+ Given Blog has attributes title, author
151
+
152
+ When I instantiate a Blog with {:title => "post!", :author => 'Ryan'}
153
+ And I configure horizontal_separator with '='
154
+ And table_print Blog
155
+ Then the output should contain
156
+ """
157
+ TITLE | AUTHOR
158
+ ======|=======
159
+ post! | Ryan
160
+ """
161
+
162
+ Scenario: Removing the horizontal separator
163
+ Given a class named Blog
164
+
165
+ Given Blog has attributes title, author
166
+
167
+ When I instantiate a Blog with {:title => "post!", :author => 'Ryan'}
168
+ And I turn the horizontal separator off
169
+ And table_print Blog
170
+ Then the output should contain
171
+ """
172
+ TITLE | AUTHOR
173
+ post! | Ryan
174
+ """
175
+
117
176
  Scenario: Setting the column separator
118
177
  Given a class named Blog
119
178
 
@@ -0,0 +1,27 @@
1
+ Feature: Printing arrays
2
+
3
+ Scenario: An array of arrays
4
+ Given an array of arrays named data with
5
+ | First post! | Ryan |
6
+ | Second post! | John |
7
+ When I table_print data
8
+ Then the output should contain
9
+ """
10
+ 0 | 1
11
+ -------------|-----
12
+ First post! | Ryan
13
+ Second post! | John
14
+ """
15
+
16
+ Scenario: Choosing columns by index
17
+ Given an array of arrays named data with
18
+ | First post! | Ryan |
19
+ | Second post! | John |
20
+ When I table_print data, ["1"]
21
+ Then the output should contain
22
+ """
23
+ 1
24
+ ----
25
+ Ryan
26
+ John
27
+ """
@@ -9,8 +9,8 @@ Feature: Sensible defaults
9
9
 
10
10
  Scenario: A simple object
11
11
  Given a class named Foo
12
- Given Foo has attributes herp
13
- Given Foo has a method named derp with lambda{"hurrrrr"}
12
+ Given Foo has attributes mood
13
+ Given Foo has a method named rallying_cry with lambda{"tally ho!"}
14
14
 
15
15
  Given a class named Foo::Blog
16
16
  Given Foo::Blog has attributes title, author
@@ -1,5 +1,9 @@
1
1
  Before do
2
2
  Sandbox.cleanup!
3
3
  TablePrint::Config.clear(:capitalize_headers)
4
+ TablePrint::Config.clear(:show_headers)
4
5
  TablePrint::Config.clear(:separator)
6
+ TablePrint::Config.clear(:horizontal_separator)
7
+ TablePrint::Config.clear(:multibyte)
8
+ TablePrint::Config.clear(:unreachable_value)
5
9
  end
@@ -25,6 +25,11 @@ Given /^a variable named (.*) with$/ do |variable, table|
25
25
  @objs.send("#{variable.downcase}=", table.hashes)
26
26
  end
27
27
 
28
+ Given /^an array of arrays named (.*) with$/ do |variable, table|
29
+ @objs ||= OpenStruct.new
30
+ @objs.send("#{variable.downcase}=", table.raw) # raw: every row is data, no header
31
+ end
32
+
28
33
  Given /^an array of structs named (.*) with$/ do |variable, table|
29
34
  @objs ||= OpenStruct.new
30
35
  struct = Struct.new(*(table.column_names.collect(&:to_sym)))
@@ -62,14 +67,30 @@ When /^I configure multibyte with (.*)$/ do |value|
62
67
  TablePrint::Config.set(:multibyte, [value == "true"])
63
68
  end
64
69
 
70
+ When /^I configure unreachable_value with '(.*)'$/ do |value|
71
+ TablePrint::Config.set(:unreachable_value, [value])
72
+ end
73
+
65
74
  When /^I configure capitalize_headers with (.*)$/ do |value|
66
75
  TablePrint::Config.set(:capitalize_headers, [value == "true"])
67
76
  end
68
77
 
78
+ When /^I configure show_headers with (.*)$/ do |value|
79
+ TablePrint::Config.set(:show_headers, [value == "true"])
80
+ end
81
+
69
82
  When /^I configure separator with '(.*)'$/ do |value|
70
83
  TablePrint::Config.set(:separator, [value])
71
84
  end
72
85
 
86
+ When /^I configure horizontal_separator with '(.*)'$/ do |value|
87
+ TablePrint::Config.set(:horizontal_separator, [value])
88
+ end
89
+
90
+ When /^I turn the horizontal separator off$/ do
91
+ TablePrint::Config.set(:horizontal_separator, [nil])
92
+ end
93
+
73
94
  When /^configure (.*) with (.*)$/ do |klass, config|
74
95
  klass = Sandbox.const_get_from_string(klass)
75
96
  TablePrint::Config.set(klass, eval(config))
@@ -90,7 +111,7 @@ Then /^the output should contain$/ do |string|
90
111
  output = @r.each_line.to_a
91
112
 
92
113
  output.zip(string.split("\n")).each do |actual, expected|
93
- actual.gsub(/\s/m, "").split(//).sort.join.should == expected.gsub(" ", "").split(//).sort.join
114
+ expect(actual.gsub(/\s/m, "").split(//).sort.join).to eq expected.gsub(" ", "").split(//).sort.join
94
115
  end
95
116
  end
96
117
 
@@ -34,7 +34,7 @@ module TablePrint
34
34
  end
35
35
 
36
36
  def data_width
37
- if multibyte_count
37
+ @data_width ||= if multibyte_count
38
38
  [
39
39
  name.each_char.collect{|c| c.bytesize == 1 ? 1 : 2}.inject(0, &:+),
40
40
  Array(data).compact.collect(&:to_s).collect{|m| m.each_char.collect{|n| n.bytesize == 1 ? 1 : 2}.inject(0, &:+)}.max
@@ -48,13 +48,18 @@ module TablePrint
48
48
  end
49
49
 
50
50
  def width
51
+ [configured_width, 0].max # a negative width has nothing to print, and crashes the formatters
52
+ end
53
+
54
+ private
55
+
56
+ def configured_width
51
57
  return fixed_width if fixed_width
52
58
 
53
59
  width = [(default_width || max_width), data_width].min
54
60
  [(min_width || 0), width].max
55
61
  end
56
62
 
57
- private
58
63
  def max_width
59
64
  TablePrint::Config.max_width
60
65
  end
@@ -5,14 +5,21 @@ module TablePrint
5
5
  DEFAULT_TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
6
6
  DEFAULT_IO = $stdout
7
7
  DEFAULT_CAPITALIZE_HEADERS = true
8
+ DEFAULT_SHOW_HEADERS = true
8
9
  DEFAULT_SEPARATOR = "|"
10
+ DEFAULT_HORIZONTAL_SEPARATOR = "-"
11
+ DEFAULT_MULTIBYTE = false
12
+ DEFAULT_UNREACHABLE_VALUE = "Method Missing"
9
13
 
10
14
  @@max_width = DEFAULT_MAX_WIDTH
11
15
  @@time_format = DEFAULT_TIME_FORMAT
12
- @@multibyte = false
16
+ @@multibyte = DEFAULT_MULTIBYTE
17
+ @@unreachable_value = DEFAULT_UNREACHABLE_VALUE
13
18
  @@io = DEFAULT_IO
14
- @@capitalize_headers = true
19
+ @@capitalize_headers = DEFAULT_CAPITALIZE_HEADERS
20
+ @@show_headers = DEFAULT_SHOW_HEADERS
15
21
  @@separator = DEFAULT_SEPARATOR
22
+ @@horizontal_separator = DEFAULT_HORIZONTAL_SEPARATOR
16
23
 
17
24
  @@klasses = {}
18
25
 
@@ -24,8 +31,17 @@ module TablePrint
24
31
  end
25
32
  end
26
33
 
34
+ # A copy, because resolving options consumes them: ConfigResolver reads an
35
+ # :include or :except out of the hash it's given with Hash#delete, which
36
+ # would empty the stored config after a single print. The copy is shallow on
37
+ # purpose - nested option hashes are never mutated, and a deep copy would
38
+ # break a config holding a lambda column.
27
39
  def self.for(klass)
28
- @@klasses.fetch(klass) {}
40
+ config = @@klasses.fetch(klass) {}
41
+ return config.dup if config.is_a?(Hash)
42
+ return config unless config.is_a?(Array)
43
+
44
+ config.collect { |option| option.is_a?(Hash) ? option.dup : option }
29
45
  end
30
46
 
31
47
  def self.clear(klass)
@@ -53,6 +69,17 @@ module TablePrint
53
69
  @@multibyte = width
54
70
  end
55
71
 
72
+ def self.unreachable_value
73
+ @@unreachable_value
74
+ end
75
+
76
+ # what to show in a cell whose value can't be reached - no such method, no
77
+ # such hash key - or nil to leave those cells blank. A value that exists and
78
+ # happens to be nil prints blank either way.
79
+ def self.unreachable_value=(value)
80
+ @@unreachable_value = value
81
+ end
82
+
56
83
  def self.time_format
57
84
  @@time_format
58
85
  end
@@ -69,6 +96,14 @@ module TablePrint
69
96
  @@capitalize_headers = caps
70
97
  end
71
98
 
99
+ def self.show_headers
100
+ @@show_headers
101
+ end
102
+
103
+ def self.show_headers=(show)
104
+ @@show_headers = show
105
+ end
106
+
72
107
  def self.separator
73
108
  @@separator
74
109
  end
@@ -77,6 +112,18 @@ module TablePrint
77
112
  @@separator = separator
78
113
  end
79
114
 
115
+ def self.horizontal_separator
116
+ @@horizontal_separator
117
+ end
118
+
119
+ # the character under the header, or nil for no line at all
120
+ def self.horizontal_separator=(separator)
121
+ unless separator.nil? or separator.to_s.length == 1
122
+ raise StandardError.new("horizontal_separator must be a single character, or nil for no line, got #{separator.inspect}")
123
+ end
124
+ @@horizontal_separator = separator
125
+ end
126
+
80
127
  def self.io
81
128
  @@io
82
129
  end
@@ -21,12 +21,8 @@ module TablePrint
21
21
  # process special symbols
22
22
 
23
23
  @included_columns.concat [get_and_remove(options, :include)].flatten
24
- @included_columns.map! do |option|
25
- if option.is_a? Column
26
- option
27
- else
28
- option_to_column(option)
29
- end
24
+ @included_columns = @included_columns.flat_map do |option|
25
+ option.is_a?(Column) ? [option] : options_to_columns(option)
30
26
  end
31
27
 
32
28
  @included_columns.each do |c|
@@ -38,7 +34,7 @@ module TablePrint
38
34
 
39
35
  # anything that isn't recognized as a special option is assumed to be a column name
40
36
  options.compact!
41
- @only_columns = options.collect { |name| option_to_column(name) } unless options.empty?
37
+ @only_columns = options.flat_map { |option| options_to_columns(option) } unless options.empty?
42
38
  end
43
39
 
44
40
  def get_and_remove(options_array, key)
@@ -57,6 +53,14 @@ module TablePrint
57
53
  option_of_interest
58
54
  end
59
55
 
56
+ # One hash can name several columns - {:title => {...}, :author => {...}} -
57
+ # which is what you get when you write them without braces of their own.
58
+ def options_to_columns(option)
59
+ return [option_to_column(option)] unless option.is_a?(Hash) and option.length > 1
60
+
61
+ option.collect { |name, value| option_to_column(name => value) }
62
+ end
63
+
60
64
  def option_to_column(option)
61
65
  if option.is_a? Hash
62
66
  name = option.keys.first
@@ -69,12 +73,19 @@ module TablePrint
69
73
  option = {:name => option}
70
74
  end
71
75
 
76
+ # deprecated
72
77
  if option.has_key? :width
73
78
  option[:default_width] = option.delete(:width)
74
79
  end
75
80
 
81
+ # :max_width is the preferred name now
82
+ if option.has_key? :max_width
83
+ option[:default_width] = option.delete(:max_width)
84
+ end
85
+
76
86
  if option.has_key? :display_name
77
- option[:display_method] = option[:name]
87
+ # the key names the method, unless the caller named one themselves
88
+ option[:display_method] ||= option[:name]
78
89
  option[:name] = option.delete(:display_name)
79
90
  end
80
91
 
@@ -43,7 +43,7 @@ module TablePrint
43
43
  elsif target.respond_to? method
44
44
  cell_value ||= target.send(method)
45
45
  else
46
- cell_value = "Method Missing"
46
+ cell_value = TablePrint::Config.unreachable_value
47
47
  end
48
48
  cells[@column_names_by_display_method[display_method]] = cell_value
49
49
  end
@@ -35,6 +35,7 @@ module TablePrint
35
35
 
36
36
  value = value.to_s
37
37
  return value unless value.length > width
38
+ return value[0, width] if width < 4 # no room for the ellipsis
38
39
 
39
40
  "#{value[0..width-4]}..."
40
41
  end
@@ -19,6 +19,15 @@ module TablePrint
19
19
 
20
20
  return target.keys if target.is_a? Hash
21
21
  return target.members.collect(&:to_sym) if target.is_a? Struct
22
+ return target.to_h.keys if defined?(OpenStruct) and target.is_a? OpenStruct
23
+
24
+ case target
25
+ when String, Symbol, Numeric, Array, TrueClass, FalseClass, Range
26
+ # Show these as-is in a single VALUE column before hittint the loop below. Which call
27
+ # their methods instead, including String#clear, which empties the string.
28
+ # Arrays included for rows from CSV.read or .pluck, which hold strings.
29
+ return [{"value" => lambda { |value| value }}]
30
+ end
22
31
 
23
32
  methods = []
24
33
  target.methods.each do |method_name|
@@ -62,9 +62,12 @@ module TablePrint
62
62
  end
63
63
 
64
64
  def horizontal_separator
65
+ character = TablePrint::Config.horizontal_separator
66
+ return nil unless character
67
+
65
68
  columns.collect do |column|
66
- '-' * column.width
67
- end.join("-#{TablePrint::Config.separator}-")
69
+ character * column.width
70
+ end.join("#{character}#{TablePrint::Config.separator}#{character}")
68
71
  end
69
72
 
70
73
  def header
@@ -1,4 +1,4 @@
1
1
  module TablePrint
2
- VERSION = "1.5.7"
2
+ VERSION = "1.6.0"
3
3
  end
4
4
 
data/lib/table_print.rb CHANGED
@@ -17,7 +17,16 @@ module TablePrint
17
17
  end
18
18
 
19
19
  def initialize(data, options={})
20
- @data = Array(data).compact
20
+ # a single hash is one row, not a list of [key, value] pairs
21
+ @data = data.is_a?(Hash) ? [data] : Array(data).compact
22
+
23
+ # Convert array of arrays into hashes
24
+ @data = @data.collect { |row| Array(row).each_with_index.to_h { |cell, i| [i.to_s, cell] } } if @data.first.is_a?(Array)
25
+
26
+ # Columns are looked up by name, so a key that isn't already a string or a
27
+ # symbol can never be found
28
+ @data = @data.collect { |row| stringify_exotic_keys(row) } if @data.first.is_a?(Hash)
29
+
21
30
  @options = options
22
31
  @columns = nil
23
32
  @start_time = Time.now
@@ -36,7 +45,7 @@ module TablePrint
36
45
  end
37
46
 
38
47
  # copy data from original objects into the group
39
- group_data = (@data.first.is_a?(Hash) || @data.first.is_a?(Struct)) ? [@data] : @data
48
+ group_data = (@data.first.is_a?(Hash) || @data.first.is_a?(Struct) || @data.first.is_a?(Range)) ? [@data] : @data
40
49
  group_data.each do |data|
41
50
  group.add_children(Fingerprinter.new.lift(columns, data))
42
51
  end
@@ -46,7 +55,10 @@ module TablePrint
46
55
  return "No data." if group.columns.empty?
47
56
 
48
57
  # turn everything into a string for output
49
- [group.header, group.horizontal_separator, group.format].join("\n")
58
+ # the line under the header has nothing to be under when headers are off
59
+ lines = [group.format]
60
+ lines.unshift(group.header, group.horizontal_separator) if TablePrint::Config.show_headers
61
+ lines.compact.join("\n")
50
62
  end
51
63
 
52
64
  def message
@@ -58,6 +70,14 @@ module TablePrint
58
70
  end
59
71
 
60
72
  private
73
+ def stringify_exotic_keys(row)
74
+ # Skip rows that aren't affected because transform_keys returns a plain Hash,
75
+ # which would strip a subclass like HashWithIndifferentAccess of the lookup a
76
+ # lambda column may rely on
77
+ return row if row.keys.all? { |key| key.is_a?(String) || key.is_a?(Symbol) }
78
+ row.transform_keys { |key| key.is_a?(String) || key.is_a?(Symbol) ? key : key.to_s }
79
+ end
80
+
61
81
  def configged?
62
82
  !!Config.for(@data.first.class)
63
83
  end
data/spec/column_spec.rb CHANGED
@@ -6,24 +6,24 @@ describe Column do
6
6
  let(:c) {Column.new(:data => ["Once upon a time", "there was a dark and stormy night"], :name => :tagline)}
7
7
 
8
8
  it "remembers its name as a string" do
9
- c.name.should == "tagline"
9
+ expect(c.name).to eq "tagline"
10
10
  end
11
11
 
12
12
  it "exposes the array of data representing the column" do
13
- c.data.should == ["Once upon a time", "there was a dark and stormy night"]
13
+ expect(c.data).to eq ["Once upon a time", "there was a dark and stormy night"]
14
14
  end
15
15
 
16
16
  describe "#add_formatter" do
17
17
  it "stores the formatter" do
18
18
  f = {}
19
19
  c.add_formatter(f)
20
- c.formatters.should == [f]
20
+ expect(c.formatters).to eq [f]
21
21
  end
22
22
  end
23
23
 
24
24
  describe "#formatter=" do
25
25
  it "adds the formatters individually" do
26
- c.should_receive(:add_formatter).twice
26
+ expect(c).to receive(:add_formatter).twice
27
27
  c.formatters = [{}, {}]
28
28
  end
29
29
  end
@@ -31,62 +31,77 @@ describe Column do
31
31
  describe "#display_method" do
32
32
  it "returns the column's display method as a string" do
33
33
  c = Column.new(:display_method => :boofar)
34
- c.display_method.should == "boofar"
34
+ expect(c.display_method).to eq "boofar"
35
35
  end
36
36
 
37
37
  it "doesn't turn a lambda display method into a string" do
38
38
  lam = lambda{}
39
39
  c = Column.new(:display_method => lam)
40
- c.display_method.should == lam
40
+ expect(c.display_method).to eq lam
41
41
  end
42
42
 
43
43
  it "defaults to the column name" do
44
44
  c = Column.new(:name => :boofar)
45
- c.display_method.should == "boofar"
45
+ expect(c.display_method).to eq "boofar"
46
46
  end
47
47
  end
48
48
 
49
49
  describe "#data_width" do
50
50
  it "reflects the width of the data set" do
51
- c.data_width.should == 33
51
+ expect(c.data_width).to eq 33
52
52
  end
53
53
 
54
54
  it "includes the title in the calculation" do
55
55
  c.name = "a horse is a horse of course of course"
56
- c.data_width.should == 38
56
+ expect(c.data_width).to eq 38
57
+ end
58
+ end
59
+
60
+ describe "#data_width" do
61
+ it "scans the data only once, however many times it's asked" do
62
+ data = ["Once upon a time"]
63
+ column = Column.new(:name => :tagline, :data => data)
64
+
65
+ expect(data).to receive(:compact).once.and_call_original
66
+ 3.times { column.data_width }
57
67
  end
58
68
  end
59
69
 
60
70
  describe "#width" do
71
+ it "never goes below zero" do
72
+ expect(Column.new(:name => :title, :fixed_width => -3).width).to eq 0
73
+ expect(Column.new(:name => :title, :min_width => -10, :default_width => -5).width).to eq 0
74
+ end
75
+
61
76
  context "when default width is specified" do
62
77
  it "uses the default width" do
63
78
  c.default_width = 10
64
- c.stub(:data_width => 15)
65
- c.stub(:max_width => 20)
66
- c.width.should == 10
79
+ allow(c).to receive(:data_width).and_return(15)
80
+ allow(c).to receive(:max_width).and_return(20)
81
+ expect(c.width).to eq 10
67
82
  end
68
83
 
69
84
  it "isn't limited by the config width" do
70
85
  c.default_width = 40
71
- c.stub(:data_width => 50)
72
- c.stub(:max_width => 20)
73
- c.width.should == 40
86
+ allow(c).to receive(:data_width).and_return(50)
87
+ allow(c).to receive(:max_width).and_return(20)
88
+ expect(c.width).to eq 40
74
89
  end
75
90
  end
76
91
 
77
92
  context "When default width is not specified" do
78
93
  it "uses the data width" do
79
94
  c.default_width = nil
80
- c.stub(:data_width => 10)
81
- c.stub(:max_width => 20)
82
- c.width.should == 10
95
+ allow(c).to receive(:data_width).and_return(10)
96
+ allow(c).to receive(:max_width).and_return(20)
97
+ expect(c.width).to eq 10
83
98
  end
84
99
 
85
100
  it "is limited by the config width" do
86
101
  c.default_width = nil
87
- c.stub(:data_width => 30)
88
- c.stub(:max_width => 20)
89
- c.width.should == 20
102
+ allow(c).to receive(:data_width).and_return(30)
103
+ allow(c).to receive(:max_width).and_return(20)
104
+ expect(c.width).to eq 20
90
105
  end
91
106
  end
92
107
  end