Class: Bundler::Stats::Printer
- Inherits:
-
Object
- Object
- Bundler::Stats::Printer
- Defined in:
- lib/bundler/stats/printer.rb
Overview
this is somewhat duplicative of the table_print gem, but tbh I like that we don’t have many dependencies yet, so I’d rather keep it this way.
Constant Summary collapse
- MIN_COL_SIZE =
10
- BORDERS =
{ on: { corner: "+", horizontal: "-", vertical: "|" }, off: { corner: " ", horizontal: " ", vertical: " " }, }
Instance Attribute Summary collapse
-
#borders ⇒ Object
Returns the value of attribute borders.
-
#data ⇒ Object
Returns the value of attribute data.
-
#headers ⇒ Object
Returns the value of attribute headers.
Instance Method Summary collapse
- #column_widths(table_data) ⇒ Object
-
#initialize(headers: nil, data: [], borders: true) ⇒ Printer
constructor
A new instance of Printer.
- #terminal_width ⇒ Object
- #to_s ⇒ Object
Constructor Details
Instance Attribute Details
#borders ⇒ Object
Returns the value of attribute borders.
4 5 6 |
# File 'lib/bundler/stats/printer.rb', line 4 def borders @borders end |
#data ⇒ Object
Returns the value of attribute data.
4 5 6 |
# File 'lib/bundler/stats/printer.rb', line 4 def data @data end |
#headers ⇒ Object
Returns the value of attribute headers.
4 5 6 |
# File 'lib/bundler/stats/printer.rb', line 4 def headers @headers end |
Instance Method Details
#column_widths(table_data) ⇒ Object
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 |
# File 'lib/bundler/stats/printer.rb', line 45 def column_widths(table_data) num_cols = table_data.first.length chrome = 2 + 2 + (num_cols - 1) * 3 # doesn't fit at all if chrome + (num_cols * MIN_COL_SIZE) > terminal_width raise ArgumentError, "Table smooshed. Refusing to print table." end data_widths = 0.upto(num_cols - 1).map do |idx| max_width(table_data.map { |row| row[idx] }) end # fits comfortably if data_widths.inject(&:+) + chrome < terminal_width return data_widths end free_space = terminal_width free_space -= chrome free_space -= MIN_COL_SIZE * num_cols # fit uncomfortably widths = [MIN_COL_SIZE] * num_cols data_widths.each_with_index do |width, idx| next unless width > widths[idx] allocated = [width, free_space].min if allocated > 0 widths[idx] += allocated free_space -= allocated end end widths end |
#terminal_width ⇒ Object
39 40 41 42 43 |
# File 'lib/bundler/stats/printer.rb', line 39 def terminal_width Integer(Kernel.send(:"`", "tput cols")) rescue StandardError 80 end |
#to_s ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/bundler/stats/printer.rb', line 19 def to_s table_data = ([headers] + data).compact col_widths = column_widths(table_data) lines = [] lines << separator_row(col_widths) if headers lines << aligned_row(headers, col_widths) lines << separator_row(col_widths) end data.each do |row| lines += split_rows(row, col_widths) end lines << separator_row(col_widths) lines.join("\n") end |