Skip to content

Instantly share code, notes, and snippets.

@jtanium
Last active December 11, 2015 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtanium/4599448 to your computer and use it in GitHub Desktop.
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.
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