-
-
Save colin/209896 to your computer and use it in GitHub Desktop.
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
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