pretty tables for rails models
Inspired by: http://blog.caboo.se/articles/2006/06/10/pretty-tables-for-ruby-objects
It gives a MySQL-command-line-client style textual view of data stored in your Rails database. The syntax worked like this:
1 2 Something.find(:all, :conditions => βwhateverβ).pretty_print
1 2 class Array 3 4 protected 5 6 def columnized_row(fields, sized) 7 r = [] 8 fields.each_with_index do |f, i| 9 r << sprintf(β?%0-#{sized[i]}sβ, f.to_s.gsub(/\n|\r/, ββ).slice(0, sized[i])) 10 end 11 r.join(β | β) 12 end 13 14 public 15 16 def columnized(options = {}) 17 sized = {} 18 self.each do |row| 19 row.attributes.values.each_with_index do |value, i| 20 sized[i] = [sized[i].to_i, row.attributes.keys[i].length, value.to_s.length].max 21 sized[i] = [options[:max_width], sized[i].to_i].min if options[:max_width] 22 end 23 end 24 25 table = [] 26 table << header = columnized_row(self.first.attributes.keys, sized) 27 table << header.gsub(/./, β-β) 28 self.each { |row| table << columnized_row(row.attributes.values, sized) } 29 table.join(β?\nβ) 30 end 31 end 32 33 class ActiveRecord::Base 34 def columnized(options = {}) 35 [*self].columnized(options) 36 end 37 end 38
To use:
1 2 >> puts Post.find(:all).columnized(:max_width => 10) 3 updated_at | title | private | url | thumb | metadata | movie | id | views | content | user_id | created_at 4 ββββββββββββββββββββββββββββββββββββββββββ 5 Wed May 31 | tetwer | 0 | | | | | 909 | 0 | video:xyzz | 1 | Wed May 31 6 Wed May 31 | bbbb | 0 | | | | | 1 | 15 | // descrip | 1 | Tue May 23 7 Wed May 31 | cxzcxzx | 0 | | | | | 906 | 19 | // descrip | 1 | Tue May 23 8 Wed May 31 | jklklkl; | 0 | | | | | 907 | 35 | // descrip | 1 | Tue May 23
If you want to use it with your project, put the code into lib/columnized.rb, use require βcolumnizedβ, and youβre ready to roll. Unlike courtenayβs version, mine only supports max_width, but I didnβt consider changing the column separator too important.