DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Pretty Tables For Rails Models

06.12.2006
| 10497 views |
  • submit to reddit
        From http://www.rubyinside.com/columnized-text-datasets-in-rails-71.html:
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:
Something.find(:all, :conditions => ‘whatever‘).pretty_print

class Array

  protected

    def columnized_row(fields, sized)
      r = []
      fields.each_with_index do |f, i|
        r << sprintf(�%0-#{sized[i]}s“, f.to_s.gsub(/\n|\r/, ‘’).slice(0, sized[i]))
      end
      r.join(’ | ‘)
    end

  public

  def columnized(options = {})
    sized = {}
    self.each do |row|
      row.attributes.values.each_with_index do |value, i|
        sized[i] = [sized[i].to_i, row.attributes.keys[i].length, value.to_s.length].max
        sized[i] = [options[:max_width], sized[i].to_i].min if options[:max_width]
      end
    end

    table = []
    table << header = columnized_row(self.first.attributes.keys, sized)
    table << header.gsub(/./, ‘-‘)
    self.each { |row| table << columnized_row(row.attributes.values, sized) }
    table.join(�\n“)
  end
end

class ActiveRecord::Base
  def columnized(options = {})
    [*self].columnized(options)
  end
end


To use:
>> puts Post.find(:all).columnized(:max_width => 10)
updated_at | title      | private | url | thumb      | metadata | movie      | id  | views | content    | user_id | created_at
——————————————————————————————————————————
Wed May 31 | tetwer     | 0       |     |            |          |            | 909 | 0     | video:xyzz | 1       | Wed May 31
Wed May 31 | bbbb       | 0       |     |            |          |            | 1   | 15    | // descrip | 1       | Tue May 23
Wed May 31 | cxzcxzx    | 0       |     |            |          |            | 906 | 19    | // descrip | 1       | Tue May 23
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.