Skip to content

Instantly share code, notes, and snippets.

@colin
Forked from eladmeidar/ascii_table.rb
Created October 14, 2009 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save colin/209896 to your computer and use it in GitHub Desktop.
Save colin/209896 to your computer and use it in GitHub Desktop.
class Array
require 'terminal-table/import'
# Convert an array of instances to an ascii table using the "terminal-table" gem on gemcutter.org
def to_ascii_table(attributes_set = [])
begin
raise "All items must be of the same class, found #{self.collect(&:class).uniq.to_sentence}" if self.collect(&:class).uniq.size != 1
# Get a list of all existing attributes from the list.
if attributes_set.blank?
include_attributes = self.first.attributes.stringify_keys!.keys
else
include_attributes = attributes_set.collect(&:to_s) & self.first.methods
end
ascii_table = table do |t|
t.headings = include_attributes.collect(&:humanize)
self.each do |item|
new_row = []
include_attributes.each do |attr_name|
new_row << item.send(attr_name.to_sym)
end
t.add_row new_row
end
end
ascii_table
rescue Exception => e
puts "Error: #{e}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment