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.
- checksums.yaml +4 -4
- data/.github/workflows/ci.yml +33 -0
- data/LICENSE.txt +1 -1
- data/README.md +291 -0
- data/Rakefile +6 -40
- data/bin/console +237 -0
- data/features/adding_columns.feature +19 -4
- data/features/configuring_output.feature +59 -0
- data/features/printing_array.feature +27 -0
- data/features/sensible_defaults.feature +2 -2
- data/features/support/step_definitions/before.rb +4 -0
- data/features/support/step_definitions/steps.rb +22 -1
- data/lib/table_print/column.rb +7 -2
- data/lib/table_print/config.rb +50 -3
- data/lib/table_print/config_resolver.rb +19 -8
- data/lib/table_print/fingerprinter.rb +1 -1
- data/lib/table_print/formatter.rb +1 -0
- data/lib/table_print/printable.rb +9 -0
- data/lib/table_print/row_group.rb +5 -2
- data/lib/table_print/version.rb +1 -1
- data/lib/table_print.rb +23 -3
- data/spec/column_spec.rb +36 -21
- data/spec/config_resolver_spec.rb +171 -64
- data/spec/config_spec.rb +87 -10
- data/spec/data_shapes_spec.rb +455 -0
- data/spec/fingerprinter_spec.rb +64 -42
- data/spec/formatter_spec.rb +15 -9
- data/spec/hash_extensions_spec.rb +2 -2
- data/spec/printable_spec.rb +16 -6
- data/spec/returnable_spec.rb +5 -5
- data/spec/row_group_spec.rb +73 -55
- data/spec/spec_helper.rb +11 -5
- data/spec/table_print_spec.rb +131 -17
- data/table_print.gemspec +6 -6
- metadata +46 -38
- data/.document +0 -5
- data/.travis.yml +0 -9
- data/README.rdoc +0 -209
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 9625370fe7e9fa3c99f3d0629b6ce03dc843c4817b31ae65ce5b12b92e6ad63b
|
|
4
|
+
data.tar.gz: 7843c148ba5df7abbbc133d7bd085be6f372239eb34f5f81d27319851c66afff
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 1239d674fffd74e95cc73f8b75ca8ca8ed8e6166d5bb70df11c341b6c2824cd810d76f22ca967d3628ff81e64de6169a851cc88ab7d35cc2793597209f58d60e
|
|
7
|
+
data.tar.gz: 1af629ea6ed47da11971ee6fe0ffdd30178fb506147c4a19c5cec6e8d7b62bbcd65b4e41f365896e502f72c73c4b64e9ed03f64b88915835ae98ec0073ae534f
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on: [push, pull_request]
|
|
4
|
+
|
|
5
|
+
jobs:
|
|
6
|
+
test:
|
|
7
|
+
name: Ruby ${{ matrix.ruby-version }}
|
|
8
|
+
runs-on: ubuntu-latest
|
|
9
|
+
|
|
10
|
+
# Ruby 4.1 is still a preview, so let it report without failing the build.
|
|
11
|
+
continue-on-error: ${{ matrix.ruby-version == 'head' }}
|
|
12
|
+
|
|
13
|
+
strategy:
|
|
14
|
+
fail-fast: false
|
|
15
|
+
matrix:
|
|
16
|
+
# Every branch in normal or security maintenance, plus the next preview.
|
|
17
|
+
# https://www.ruby-lang.org/en/downloads/branches/
|
|
18
|
+
ruby-version:
|
|
19
|
+
- "3.3" # security maintenance until 2027-03
|
|
20
|
+
- "3.4" # normal maintenance
|
|
21
|
+
- "4.0" # current
|
|
22
|
+
- head # 4.1-preview
|
|
23
|
+
- jruby # latest 10.x
|
|
24
|
+
|
|
25
|
+
steps:
|
|
26
|
+
- uses: actions/checkout@v5
|
|
27
|
+
- name: Set up Ruby ${{ matrix.ruby-version }}
|
|
28
|
+
uses: ruby/setup-ruby@v1
|
|
29
|
+
with:
|
|
30
|
+
ruby-version: ${{ matrix.ruby-version }}
|
|
31
|
+
bundler-cache: true # 'bundle install' and cache
|
|
32
|
+
- name: Run tests
|
|
33
|
+
run: bundle exec rake
|
data/LICENSE.txt
CHANGED
data/README.md
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
# table_print
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
TablePrint shows objects in nicely formatted columns for easy reading. It even lets you nest other tables of related objects, contextualizing data across tables. It's incredibly flexible, yet simple, making it easy to see exactly the data you care about.
|
|
6
|
+
|
|
7
|
+
This [three minute screencast](http://tableprintgem.com) will give you a quick overview of table_print's most powerful features and how to use them.
|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
# Install as a standalone gem
|
|
15
|
+
$ gem install table_print
|
|
16
|
+
|
|
17
|
+
# Or install within rails
|
|
18
|
+
In your Gemfile: gem "table_print"
|
|
19
|
+
$ bundle install
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
# Outside rails
|
|
26
|
+
$ irb
|
|
27
|
+
> require 'table_print'
|
|
28
|
+
> tp array_of_objects, options
|
|
29
|
+
|
|
30
|
+
# Inside rails, the gem has already been required by your Gemfile so all you need to do is
|
|
31
|
+
$ rails c
|
|
32
|
+
> tp array_of_objects, options
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
You should see something like this:
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
> tp Book.all
|
|
39
|
+
AUTHOR | SUMMARY | TITLE
|
|
40
|
+
------------------|---------------------------------|------------------
|
|
41
|
+
Michael Connelly | Another book by Michael Con... | The Fifth Witness
|
|
42
|
+
Manning Marable | From acclaimed historian Ma... | Malcolm X
|
|
43
|
+
Tina Fey | Worth it. -Trees | Bossypants
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
TablePrint tries to use sensible defaults to choose the columns to show. If you're inspecting ActiveRecord objects, it uses the ActiveRecord column names. You can customize the output to show fewer columns, or show other methods you've written on your model. Use symbols or strings to reference the columns.
|
|
47
|
+
|
|
48
|
+
```ruby
|
|
49
|
+
# Maybe you store a user's hourly rate but you want to see their yearly income
|
|
50
|
+
tp User.limit(30), :include => :yearly_income, :except => :hourly_rate
|
|
51
|
+
|
|
52
|
+
# Maybe all you care about is their mailing info
|
|
53
|
+
tp User.limit(30), :address, 'city', 'state', :zip
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
If you're not using ActiveRecord, the TablePrint default is to show all the methods defined directly on your object (nothing from superclasses/mixins). If the objects are strings, symbols, numbers, booleans, or ranges, each one is shown in a single VALUE column instead:
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
> tp ["alice", "bob"]
|
|
60
|
+
VALUE
|
|
61
|
+
-----
|
|
62
|
+
alice
|
|
63
|
+
bob
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Hashes use their keys as columns. An array of hashes prints one row per hash, and a single hash prints as one row:
|
|
67
|
+
|
|
68
|
+
```
|
|
69
|
+
> settings = {host: "db.internal", user: "app"}
|
|
70
|
+
> tp settings
|
|
71
|
+
HOST | USER
|
|
72
|
+
------------|-----
|
|
73
|
+
db.internal | app
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
An array of arrays prints as a grid: one row per inner array, with each position as a column. This works by turning each inner array into a hash like `{"0" => [...first value...], "1" => [...second value...]}`, so you can address them by index:
|
|
77
|
+
|
|
78
|
+
```
|
|
79
|
+
> rows = [["First post!", "Ryan"], ["Second post!", "John"]]
|
|
80
|
+
> tp rows
|
|
81
|
+
0 | 1
|
|
82
|
+
-------------|-----
|
|
83
|
+
First post! | Ryan
|
|
84
|
+
Second post! | John
|
|
85
|
+
|
|
86
|
+
> tp rows, "1" # just the second column
|
|
87
|
+
1
|
|
88
|
+
----
|
|
89
|
+
Ryan
|
|
90
|
+
John
|
|
91
|
+
|
|
92
|
+
> tp rows, {"0" => {:max_width => 8}} # column options work by index too
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Nested References
|
|
96
|
+
|
|
97
|
+
You can reference nested objects with the method chain required to reach them. Say you had some users who wrote books, and those books had photos.
|
|
98
|
+
|
|
99
|
+
```
|
|
100
|
+
> tp Author.limit(3), "name", "books.title", "books.photos.caption"
|
|
101
|
+
NAME | BOOKS.TITLE | BOOKS.PHOTOS.CAPTION
|
|
102
|
+
------------------|-------------------|----------------------------------
|
|
103
|
+
Michael Connelly | The Fifth Witness | Susan was running, fast, away...
|
|
104
|
+
| | Along came a spider.
|
|
105
|
+
| Malcolm X |
|
|
106
|
+
| Bossypants | Yes! Yes! A thousand times ye...
|
|
107
|
+
| | Don't see many like you aroun...
|
|
108
|
+
Carrot Top | |
|
|
109
|
+
Milton Greene | How I Learned | Once upon a time, I was a sma...
|
|
110
|
+
| | Lemons are yellow, limes are ...
|
|
111
|
+
| | Never as a woman her age. I l...
|
|
112
|
+
| Desperados | Avast.
|
|
113
|
+
| | Giraffes lived a peaceful exi...
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Column options
|
|
117
|
+
|
|
118
|
+
Pass options to individual columns through the options hash by using the display method as the hash key. Eg, if you wanted a skinny email column, cap its width:
|
|
119
|
+
|
|
120
|
+
```ruby
|
|
121
|
+
tp User.all, :email => {:max_width => 12}
|
|
122
|
+
tp User.all, :id, {:email => {:max_width => 12}}, :age
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Available column options:
|
|
126
|
+
|
|
127
|
+
- **display_method** - string/symbol/proc - used to populate the column. Can be a method name or a proc. See below.
|
|
128
|
+
- **formatters** - array of objects - each will be called in turn as the cells are printed. Must define a 'format' method. See below.
|
|
129
|
+
- **time_format** - string - passed to [strftime](https://docs.ruby-lang.org/en/master/language/strftime_formatting_rdoc.html#conversion-specifiers), only affects time columns
|
|
130
|
+
- **max_width** - integer - maximum width for this column. Overrides the global `max_width`.
|
|
131
|
+
- **fixed_width** - integer - exact width for this column
|
|
132
|
+
- **min_width** - integer - minimum width for this column
|
|
133
|
+
- **display_name** - string - useful if you want spaces in your column name
|
|
134
|
+
- **separator** - string - default is vertical bar for console and markdown, change it to a comma for CSV output
|
|
135
|
+
|
|
136
|
+
#### Display method
|
|
137
|
+
|
|
138
|
+
Columns are named after hash keys. To rename a column, use the name you want as the key, and pass the method as an option.
|
|
139
|
+
|
|
140
|
+
```ruby
|
|
141
|
+
tp User.all, :active => {:display_method => :active_in_the_past_six_months} # the User class defines active_in_the_past_six_months method
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Or keep the key and set the heading separately with `display_name`:
|
|
145
|
+
|
|
146
|
+
```ruby
|
|
147
|
+
tp User.all, :yearly_payment => {:display_name => "Yearly Pay", :display_method => lambda{|u| u.monthly_payment * 12}}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
#### Lambdas
|
|
151
|
+
|
|
152
|
+
You can pass a proc as the display_method for a column:
|
|
153
|
+
|
|
154
|
+
```ruby
|
|
155
|
+
tp User.all, :email, :monthly_payment, yearly_payment: lambda{|u| u.monthly_payment * 12}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Or if you want to pass other options along with the lambda:
|
|
159
|
+
|
|
160
|
+
```ruby
|
|
161
|
+
tp User.all, :yearly_payment => {:display_method => lambda{|u| u.monthly_payment * 12}, :max_width => 10}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
One hash can name as many columns as you like:
|
|
165
|
+
|
|
166
|
+
```ruby
|
|
167
|
+
tp User.all, :email, daily_payment: lambda { |u| u.monthly_payment / 30 }, yearly_payment: lambda { |u| u.monthly_payment * 12 }
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Braces of their own are only needed when a plain column name has to follow them, which is ruby's rule about hash
|
|
171
|
+
arguments rather than table_print's:
|
|
172
|
+
|
|
173
|
+
```ruby
|
|
174
|
+
tp User.all, :email, { daily_payment: lambda { |u| u.monthly_payment / 30} }, :monthly_payment, { yearly_payment: lambda { |u| u.monthly_payment * 12} }
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
#### Column formatters
|
|
178
|
+
|
|
179
|
+
Similar to a lambda column, you can use a column formatter to reuse code across prints. Any object with a 'format' method can be used to filter a column. This could also be used for coloring output.
|
|
180
|
+
|
|
181
|
+
```ruby
|
|
182
|
+
class NoNewlineFormatter
|
|
183
|
+
def format(value)
|
|
184
|
+
value.to_s.gsub(/\r\n/, " ")
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
tp User.all, :bio => {:formatters => [NoNewlineFormatter.new]} # strip newlines from user bios
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### HTML Output
|
|
192
|
+
|
|
193
|
+
Currently the best way to show table_print output on an HTML page is using a `<pre>` tag. You can create a helper method to send table_print output directly into your `<pre>` tag:
|
|
194
|
+
|
|
195
|
+
```ruby
|
|
196
|
+
def tp_pre data, options={}
|
|
197
|
+
content_tag :pre, TablePrint::Printer.new(data, options).table_print
|
|
198
|
+
end
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### CSV Output
|
|
202
|
+
|
|
203
|
+
Set the column separator to get an output you can save as a CSV, and turn off the line under the header so it doesn't
|
|
204
|
+
end up in the file:
|
|
205
|
+
|
|
206
|
+
```ruby
|
|
207
|
+
tp.set :separator, ","
|
|
208
|
+
tp.set :horizontal_separator, nil
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Since your CSV viewer probably already handles column widths for you, setting `max_width` to something very large will help you export your full data set. Otherwise, this CSV output will still be truncated to the default max_width of 30 characters.
|
|
212
|
+
|
|
213
|
+
### Config
|
|
214
|
+
|
|
215
|
+
Use tp.set and tp.clear to set options on a class-by-class basis.
|
|
216
|
+
|
|
217
|
+
```
|
|
218
|
+
tp.set User, :id, :email # now whenever you print users, the only columns shown will be id and email
|
|
219
|
+
|
|
220
|
+
> tp User.first
|
|
221
|
+
ID | EMAIL
|
|
222
|
+
---|------------
|
|
223
|
+
1 | foo@bar.com
|
|
224
|
+
|
|
225
|
+
# the config sets a 'baseline' for each print. You can still include/except columns:
|
|
226
|
+
> tp User.first, :except => :email
|
|
227
|
+
ID
|
|
228
|
+
--
|
|
229
|
+
17
|
|
230
|
+
|
|
231
|
+
# a specific set of columns will entirely override the baseline config:
|
|
232
|
+
> tp User.first, :first_name
|
|
233
|
+
FIRST_NAME
|
|
234
|
+
----------
|
|
235
|
+
Phooey
|
|
236
|
+
|
|
237
|
+
tp.clear User # back to square one - print all the columns we can find
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
To see the config for a given object, use tp.config_for.
|
|
241
|
+
|
|
242
|
+
```
|
|
243
|
+
> tp.set User, :id, :email
|
|
244
|
+
> tp.config_for User
|
|
245
|
+
[:id, :email]
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
You can also set global options:
|
|
249
|
+
|
|
250
|
+
```ruby
|
|
251
|
+
tp.set :max_width, 10 # no column exceeds 10 characters, unless it sets its own width
|
|
252
|
+
tp.set :time_format, "%Y" # date columns will only show the year
|
|
253
|
+
tp.set :capitalize_headers, false # don't capitalize column headers
|
|
254
|
+
tp.set :unreachable_value, "Unreachable" # what to show when the method chain to a cell is broken (default "Method Missing")
|
|
255
|
+
tp.set :unreachable_value, nil # leave those cells blank instead
|
|
256
|
+
tp.set :show_headers, false # no header row at all, and no line under it
|
|
257
|
+
tp.set :horizontal_separator, "=" # draw the line under the header with = instead of -
|
|
258
|
+
tp.set :horizontal_separator, nil # don't draw a line under the header at all
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
You can redirect output:
|
|
262
|
+
|
|
263
|
+
```ruby
|
|
264
|
+
f = File.open("users.txt", "w")
|
|
265
|
+
tp.set :io, f
|
|
266
|
+
tp User.all # written to users.txt instead of STDOUT
|
|
267
|
+
tp.clear :io
|
|
268
|
+
tp User.all # writing to STDOUT again
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### Multibyte
|
|
272
|
+
|
|
273
|
+
Unfortunately, the current approach to finding the width of multibyte strings is too slow. If you're going to be working with a lot of multibyte characters, set the multibyte option first to enable the slower yet more precise width calculation:
|
|
274
|
+
|
|
275
|
+
```ruby
|
|
276
|
+
> tp.set :multibyte, true
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
## Contributing to table_print
|
|
280
|
+
|
|
281
|
+
- Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
|
|
282
|
+
- Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
|
|
283
|
+
- Fork the project
|
|
284
|
+
- Start a feature/bugfix branch
|
|
285
|
+
- Commit and push until you are happy with your contribution
|
|
286
|
+
- Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
|
|
287
|
+
- Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
|
|
288
|
+
|
|
289
|
+
## Copyright
|
|
290
|
+
|
|
291
|
+
Copyright (c) Chris Doyle. See LICENSE.txt for further details.
|
data/Rakefile
CHANGED
|
@@ -1,48 +1,14 @@
|
|
|
1
|
-
require '
|
|
2
|
-
require 'bundler'
|
|
3
|
-
begin
|
|
4
|
-
Bundler.setup(:default, :development)
|
|
5
|
-
rescue Bundler::BundlerError => e
|
|
6
|
-
$stderr.puts e.message
|
|
7
|
-
$stderr.puts "Run `bundle install` to install missing gems"
|
|
8
|
-
exit e.status_code
|
|
9
|
-
end
|
|
10
|
-
require 'rake'
|
|
11
|
-
|
|
1
|
+
require 'bundler/setup'
|
|
12
2
|
require 'rspec/core/rake_task'
|
|
3
|
+
require 'cucumber/rake/task'
|
|
13
4
|
|
|
14
5
|
desc 'Default: run specs and cucumber features.'
|
|
15
|
-
|
|
16
|
-
task :default => [:spec, :cucumber_187]
|
|
17
|
-
else
|
|
18
|
-
task :default => [:spec, :cucumber]
|
|
19
|
-
end
|
|
6
|
+
task :default => [:spec, :cucumber]
|
|
20
7
|
|
|
21
|
-
desc
|
|
22
|
-
RSpec::Core::RakeTask.new
|
|
23
|
-
end
|
|
8
|
+
desc 'Run specs'
|
|
9
|
+
RSpec::Core::RakeTask.new(:spec)
|
|
24
10
|
|
|
25
|
-
require "cucumber/rake/task"
|
|
26
11
|
desc 'Run cucumber features'
|
|
27
12
|
Cucumber::Rake::Task.new(:cucumber) do |task|
|
|
28
|
-
task.cucumber_opts = [
|
|
29
|
-
end
|
|
30
|
-
|
|
31
|
-
desc 'Run cucumber features for ruby 1.8.7'
|
|
32
|
-
Cucumber::Rake::Task.new(:cucumber_187) do |task|
|
|
33
|
-
task.cucumber_opts = ["-t", "~@ruby19", "features"]
|
|
34
|
-
end
|
|
35
|
-
|
|
36
|
-
begin
|
|
37
|
-
require 'rdoc/task'
|
|
38
|
-
rescue LoadError
|
|
39
|
-
require 'rake/rdoctask' # deprecated in Ruby 1.9.3 but needed for Ruby 1.8.7 and JRuby
|
|
40
|
-
end
|
|
41
|
-
Rake::RDocTask.new do |rdoc|
|
|
42
|
-
version = File.exist?('VERSION') ? File.read('VERSION') : ""
|
|
43
|
-
|
|
44
|
-
rdoc.rdoc_dir = 'rdoc'
|
|
45
|
-
rdoc.title = "table_print #{version}"
|
|
46
|
-
rdoc.rdoc_files.include('README*')
|
|
47
|
-
rdoc.rdoc_files.include('lib/**/*.rb')
|
|
13
|
+
task.cucumber_opts = ['features', '--publish-quiet', '--tags', "'not @todo'"]
|
|
48
14
|
end
|
data/bin/console
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
# A REPL with table_print loaded from lib/, plus a pile of sample data.
|
|
3
|
+
#
|
|
4
|
+
# bin/console
|
|
5
|
+
# > fixtures # inventory of everything defined below
|
|
6
|
+
# > tp AUTHORS, "name", "books.title", "books.reviews.stars"
|
|
7
|
+
# > reload! # after editing lib/, without losing your session
|
|
8
|
+
|
|
9
|
+
require "bundler/setup"
|
|
10
|
+
require "table_print"
|
|
11
|
+
require "irb"
|
|
12
|
+
require "ostruct"
|
|
13
|
+
|
|
14
|
+
# Re-run every lib file. Method changes take effect; renamed or deleted methods
|
|
15
|
+
# linger until you restart, and any tp.set config is reset.
|
|
16
|
+
def quietly # re-executing files and re-assigning constants both warn
|
|
17
|
+
verbose, $VERBOSE = $VERBOSE, nil
|
|
18
|
+
yield
|
|
19
|
+
ensure
|
|
20
|
+
$VERBOSE = verbose
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def reload!
|
|
24
|
+
quietly { $LOADED_FEATURES.grep(%r{/lib/table_print}).each { |file| load file } }
|
|
25
|
+
:reloaded
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# ---------------------------------------------------------------- nested data
|
|
29
|
+
|
|
30
|
+
class Review
|
|
31
|
+
attr_accessor :stars, :body, :reviewer
|
|
32
|
+
def initialize(stars, body, reviewer = nil)
|
|
33
|
+
@stars, @body, @reviewer = stars, body, reviewer
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
class Tag
|
|
38
|
+
attr_accessor :label
|
|
39
|
+
def initialize(label) = @label = label
|
|
40
|
+
def to_s = "##{@label}" # cells are rendered with to_s, so this one reads nicely
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
class Book
|
|
44
|
+
attr_accessor :title, :pages, :published_at, :reviews, :tags
|
|
45
|
+
def initialize(title, pages, published_at, reviews = [], tags = [])
|
|
46
|
+
@title, @pages, @published_at = title, pages, published_at
|
|
47
|
+
@reviews, @tags = reviews, tags
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
class Author
|
|
52
|
+
attr_accessor :name, :books
|
|
53
|
+
def initialize(name, books = []) = (@name, @books = name, books)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Two books (one with two reviews, one with none), a single-book author, and an
|
|
57
|
+
# author with none - fan-out, blanked repeats and empty associations in one go.
|
|
58
|
+
# Also: a newline in a body, a title past max_width, a nil reviewer, multibyte.
|
|
59
|
+
AUTHORS = [
|
|
60
|
+
Author.new("alice", [
|
|
61
|
+
Book.new("Book A", 100, Time.at(0).utc,
|
|
62
|
+
[Review.new(5, "great", "zed"), Review.new(3, "ok\nwith a newline", nil)],
|
|
63
|
+
[Tag.new("scifi"), Tag.new("long")]),
|
|
64
|
+
Book.new("A Title Longer Than The Thirty Character Default", 200, Time.at(10**9).utc,
|
|
65
|
+
[], [Tag.new("short")])
|
|
66
|
+
]),
|
|
67
|
+
Author.new("日本語テキスト", [Book.new("Book C", 300, nil, [Review.new(1, "bad", "quinn")], [])]),
|
|
68
|
+
Author.new("carol", [])
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
# A reference cycle - fine to print as long as the path you ask for is finite.
|
|
72
|
+
class Node
|
|
73
|
+
attr_accessor :name, :parent
|
|
74
|
+
def initialize(name) = @name = name
|
|
75
|
+
end
|
|
76
|
+
CYCLE = [Node.new("a"), Node.new("b")]
|
|
77
|
+
CYCLE[0].parent, CYCLE[1].parent = CYCLE[1], CYCLE[0]
|
|
78
|
+
|
|
79
|
+
# ------------------------------------------------------------------ flat data
|
|
80
|
+
|
|
81
|
+
SETTINGS = { "host" => "db.internal", "user" => "app" } # one bare hash = one row
|
|
82
|
+
HASHES = [{ a: 1, b: "two" }, { a: 3, b: nil }] # symbol keys, nil cell
|
|
83
|
+
RAGGED = [{ a: 1 }, { b: 2 }] # columns come from row 0 only
|
|
84
|
+
NESTED = [{ a: 1, b: { c: 2 } }] # "b.c" raises - hashes aren't traversable
|
|
85
|
+
ODD_KEYS = [{ 1 => "one", nil => "nil", [1] => "arr" }] # non-string keys become columns
|
|
86
|
+
ROWS = [%w[a b], %w[c d], %w[e]] # grid; row 2 is short
|
|
87
|
+
# A grid whose cells aren't all strings. Objects print via to_s - Book has none,
|
|
88
|
+
# so it shows as #<Book:0x...>, while Tag defines one. Reaching into a cell with
|
|
89
|
+
# "1.title" raises: the row is a hash now, and hash keys aren't traversable.
|
|
90
|
+
# A lambda column sees that hash, so index it with a string: row["1"].title
|
|
91
|
+
GRID = [
|
|
92
|
+
["alice", Book.new("Book A", 100, Time.at(0).utc), Tag.new("scifi"), 42],
|
|
93
|
+
["bob", Book.new("Book B", 200, nil), Tag.new("short"), nil]
|
|
94
|
+
]
|
|
95
|
+
SCALARS = ["hello", :sym, 42, 3.14] # single VALUE column
|
|
96
|
+
STRUCTS = [Struct.new(:title, :author).new("First", "ryan")] # members as columns
|
|
97
|
+
BOOLS = [true, false] # prints INSPECT | TO_S
|
|
98
|
+
|
|
99
|
+
# --------------------------------------------------------- orm-shaped objects
|
|
100
|
+
|
|
101
|
+
class ARPost # class.columns whose entries respond to #name (ActiveRecord)
|
|
102
|
+
Column = Struct.new(:name)
|
|
103
|
+
def self.columns = [Column.new("id"), Column.new("title")]
|
|
104
|
+
def id = 1
|
|
105
|
+
def title = "from .columns"
|
|
106
|
+
def secret = "not shown by default"
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
class SequelPost # class.columns of symbols
|
|
110
|
+
def self.columns = [:id, :title]
|
|
111
|
+
def id = 2
|
|
112
|
+
def title = "from .columns (symbols)"
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
class MongoPost # #fields returning a hash
|
|
116
|
+
def fields = { "id" => nil, "title" => nil }
|
|
117
|
+
def id = 3
|
|
118
|
+
def title = "from #fields"
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
AR_POSTS = [ARPost.new]
|
|
122
|
+
SEQUEL_POSTS = [SequelPost.new]
|
|
123
|
+
MONGO_POSTS = [MongoPost.new]
|
|
124
|
+
|
|
125
|
+
# ------------------------------------------------- shapes that misbehave today
|
|
126
|
+
|
|
127
|
+
class Base
|
|
128
|
+
attr_accessor :title
|
|
129
|
+
def initialize(title) = @title = title
|
|
130
|
+
end
|
|
131
|
+
class Inherited < Base; end
|
|
132
|
+
INHERITED = [Inherited.new("First")] # "No data." - owner must == target.class
|
|
133
|
+
|
|
134
|
+
module Titled
|
|
135
|
+
attr_accessor :title
|
|
136
|
+
end
|
|
137
|
+
class Moduled
|
|
138
|
+
include Titled
|
|
139
|
+
def initialize(title) = @title = title
|
|
140
|
+
end
|
|
141
|
+
MODULED = [Moduled.new("First")] # "No data." - module methods are skipped too
|
|
142
|
+
|
|
143
|
+
class Proxy # permissive respond_to_missing? breaks Array(data) at the door
|
|
144
|
+
def respond_to_missing?(*) = true
|
|
145
|
+
def method_missing(name, *) = "delegated #{name}"
|
|
146
|
+
end
|
|
147
|
+
PROXIES = [Proxy.new] # raises TypeError: can't convert Proxy to Array
|
|
148
|
+
|
|
149
|
+
class Collectionish # a record that is also a collection: attrs are lost
|
|
150
|
+
include Enumerable
|
|
151
|
+
attr_accessor :name
|
|
152
|
+
def initialize(name, items) = (@name, @items = name, items)
|
|
153
|
+
def each(&block) = @items.each(&block)
|
|
154
|
+
end
|
|
155
|
+
COLLECTIONISH = Collectionish.new("mine", [1, 2]) # prints the items, not the name
|
|
156
|
+
|
|
157
|
+
OPENSTRUCTS = [OpenStruct.new(a: 1), OpenStruct.new(a: 2)] # every method is a column
|
|
158
|
+
|
|
159
|
+
# Hazards: tp calls every public arity-0 method, so printing these changes them.
|
|
160
|
+
# They're the same objects every time on purpose - print one twice and watch the
|
|
161
|
+
# damage accumulate, which is what you'd see if they were your own objects.
|
|
162
|
+
# reset! puts them all back.
|
|
163
|
+
class Counter
|
|
164
|
+
def initialize = @n = 0
|
|
165
|
+
def bump = @n += 1 # tp calls this
|
|
166
|
+
def n = @n
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
class Stateful
|
|
170
|
+
def initialize(items) = @items = items
|
|
171
|
+
def items = @items
|
|
172
|
+
def size = @items.size
|
|
173
|
+
def clear = @items.clear # tp calls this too, and empties items
|
|
174
|
+
end
|
|
175
|
+
# Printing a Stateful shows [] in the ITEMS column even though items is read
|
|
176
|
+
# before clear: the cell holds a reference to the array, and clear empties that
|
|
177
|
+
# same object before anything gets rendered.
|
|
178
|
+
|
|
179
|
+
class Exploder
|
|
180
|
+
def title = "ok"
|
|
181
|
+
def boom = raise(ArgumentError, "do not call me") # takes the whole print down
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
def reset!
|
|
185
|
+
quietly do
|
|
186
|
+
Object.const_set(:COUNTER, [Counter.new]) # constants can't be
|
|
187
|
+
Object.const_set(:STATEFUL, [Stateful.new(%w[a b])]) # assigned in a method
|
|
188
|
+
Object.const_set(:EXPLODER, [Exploder.new])
|
|
189
|
+
end
|
|
190
|
+
:reset
|
|
191
|
+
end
|
|
192
|
+
reset!
|
|
193
|
+
|
|
194
|
+
INFINITE = (1..Float::INFINITY).lazy.map { |i| i * 2 } # tp hangs: Array() never returns
|
|
195
|
+
|
|
196
|
+
# ----------------------------------------------------------------- inventory
|
|
197
|
+
|
|
198
|
+
FIXTURES = [
|
|
199
|
+
{ name: "AUTHORS", shape: "nested objects", note: "fan-out, blanks, empty assoc, multibyte, newline" },
|
|
200
|
+
{ name: "CYCLE", shape: "nested objects", note: 'reference cycle; try "name", "parent.name"' },
|
|
201
|
+
{ name: "SETTINGS", shape: "hash", note: "a single hash prints as one row" },
|
|
202
|
+
{ name: "HASHES", shape: "array of hashes", note: "symbol keys, nil cell" },
|
|
203
|
+
{ name: "RAGGED", shape: "array of hashes", note: "columns sniffed from row 0 -> Method Missing" },
|
|
204
|
+
{ name: "NESTED", shape: "array of hashes", note: 'nested hash; "b.c" raises NoMethodError' },
|
|
205
|
+
{ name: "ODD_KEYS", shape: "array of hashes", note: "non-string keys become column names" },
|
|
206
|
+
{ name: "ROWS", shape: "array of arrays", note: "grid; short row 2 shows Method Missing" },
|
|
207
|
+
{ name: "GRID", shape: "array of arrays", note: 'mixed cells; try {"t" => lambda{|r| r["1"].title}}' },
|
|
208
|
+
{ name: "SCALARS", shape: "array of scalars",note: "single VALUE column, inputs unharmed" },
|
|
209
|
+
{ name: "STRUCTS", shape: "array of structs",note: "members become columns" },
|
|
210
|
+
{ name: "BOOLS", shape: "array of scalars",note: "prints INSPECT | TO_S" },
|
|
211
|
+
{ name: "AR_POSTS", shape: "orm shim", note: "class.columns with #name" },
|
|
212
|
+
{ name: "SEQUEL_POSTS", shape: "orm shim", note: "class.columns of symbols" },
|
|
213
|
+
{ name: "MONGO_POSTS", shape: "orm shim", note: "#fields hash" },
|
|
214
|
+
{ name: "INHERITED", shape: "misbehaves", note: "No data. - attrs on the superclass" },
|
|
215
|
+
{ name: "MODULED", shape: "misbehaves", note: "No data. - attrs from a module" },
|
|
216
|
+
{ name: "PROXIES", shape: "misbehaves", note: "TypeError in Array(data)" },
|
|
217
|
+
{ name: "COLLECTIONISH", shape: "misbehaves", note: "unwrapped by to_a; attributes lost" },
|
|
218
|
+
{ name: "OPENSTRUCTS", shape: "misbehaves", note: "8 columns, not one of them the real attribute" },
|
|
219
|
+
{ name: "COUNTER", shape: "hazard", note: "tp calls #bump; print twice, watch it climb" },
|
|
220
|
+
{ name: "STATEFUL", shape: "hazard", note: "tp calls #clear; even the ITEMS cell reads []" },
|
|
221
|
+
{ name: "EXPLODER", shape: "hazard", note: "a raising reader kills the whole print" },
|
|
222
|
+
{ name: "INFINITE", shape: "hazard", note: "hangs forever - do not print" }
|
|
223
|
+
]
|
|
224
|
+
|
|
225
|
+
def fixtures
|
|
226
|
+
tp FIXTURES, { name: { width: 14 } }, { shape: { width: 17 } }, { note: { width: 52 } }
|
|
227
|
+
nil
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
puts "table_print #{TablePrint::VERSION} from #{File.expand_path('../lib', __dir__)}"
|
|
231
|
+
puts "fixtures -> inventory of #{FIXTURES.length} samples | reload! -> pick up lib/ edits | reset! -> restore hazards"
|
|
232
|
+
|
|
233
|
+
# Plain single-line input: the multiline editor is off by default here. Pass
|
|
234
|
+
# --multiline to bin/console to get it back for a session.
|
|
235
|
+
ARGV.unshift("--nomultiline") unless ARGV.include?("--multiline")
|
|
236
|
+
|
|
237
|
+
IRB.start(__FILE__)
|
|
@@ -1,21 +1,35 @@
|
|
|
1
1
|
Feature: Adding columns
|
|
2
2
|
Scenario: With the :include option
|
|
3
3
|
Given a class named Foo
|
|
4
|
-
Given Foo has attributes
|
|
4
|
+
Given Foo has attributes mood, blog
|
|
5
5
|
|
|
6
6
|
Given a class named Foo::Blog
|
|
7
7
|
Given Foo::Blog has attributes title, author
|
|
8
8
|
Given Foo::Blog has a class method named foo with lambda{"just testing!"}
|
|
9
9
|
Given Foo::Blog has a method named two_args with lambda{|a, b| "Called with #{a}, #{b}"}
|
|
10
10
|
|
|
11
|
-
When I instantiate a Foo with {:
|
|
11
|
+
When I instantiate a Foo with {:mood => "glad"}
|
|
12
12
|
When I instantiate a Foo::Blog with {:title => "post!", :author => 'Ryan'} and assign it to foo.blog
|
|
13
13
|
And table_print Foo, {:include => ["blog.author", "blog.title"]}
|
|
14
14
|
Then the output should contain
|
|
15
15
|
"""
|
|
16
|
-
|
|
16
|
+
MOOD | BLOG.AUTHOR | BLOG.TITLE
|
|
17
17
|
-----|-------------|-----------
|
|
18
|
-
|
|
18
|
+
glad | Ryan | post!
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
Scenario: Naming two columns in one hash
|
|
22
|
+
Given a class named Blog
|
|
23
|
+
|
|
24
|
+
Given Blog has attributes title, author
|
|
25
|
+
|
|
26
|
+
When I instantiate a Blog with {:title => "post!", :author => 'Ryan'}
|
|
27
|
+
And table_print Blog, {:shout => lambda{|b| b.title.upcase}, :quiet => lambda{|b| b.author.downcase}}
|
|
28
|
+
Then the output should contain
|
|
29
|
+
"""
|
|
30
|
+
SHOUT | QUIET
|
|
31
|
+
------|------
|
|
32
|
+
POST! | ryan
|
|
19
33
|
"""
|
|
20
34
|
|
|
21
35
|
Scenario: Providing a named proc
|
|
@@ -44,5 +58,6 @@ Feature: Adding columns
|
|
|
44
58
|
------
|
|
45
59
|
ryn
|
|
46
60
|
"""
|
|
61
|
+
@todo
|
|
47
62
|
Scenario: Using a proc as a filter (ie, overriding an existing column with a proc)
|
|
48
63
|
|