Last active
December 11, 2015 12:18
-
-
Save jtanium/4599448 to your computer and use it in GitHub Desktop.
Method to print the contents of a table. While running tests, I regularly find myself wondering what the contents of certain tables are during a test -- here's a function that prints the contents of a table to stdout.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def print_table_contents(model_klass, columns=nil) | |
columns ||= model_klass.column_names | |
column_widths = {} | |
columns.each { |col| column_widths[col] = col.to_s.length } | |
objects = model_klass.all | |
objects.each do |obj| | |
columns.each do |col| | |
len = obj[col].to_s.length | |
column_widths[col] = len if len > column_widths[col] | |
end | |
end | |
formats = {} | |
horiz_line = "+" + columns.map do |col| | |
wid = column_widths[col] | |
formats[col] = " %#{wid}s " | |
"-"*(wid+2) | |
end.join("+") + "+" | |
puts horiz_line | |
puts "|" + columns.map { |col| formats[col] % col }.join("|") + "|" | |
puts horiz_line | |
objects.each do |obj| | |
row = columns.map { |col| formats[col] % obj[col] }.join("|") | |
puts "|#{row}|" | |
end | |
puts horiz_line | |
puts | |
puts "#{model_klass.count} records" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment