Skip to content

Instantly share code, notes, and snippets.

Created May 22, 2010 16:41
Show Gist options
  • Save anonymous/410197 to your computer and use it in GitHub Desktop.
Save anonymous/410197 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
require 'rubygems'
require 'ruport'
table = Table(%w[Name Title Pets Spouse Children])
table << { "Name" => "John",
"Title" => "Accountant",
"Pets" => %w[Rufus Cheshire],
"Spouse" => "Suzy",
"Children" => "John\ Jr."
}
table << { "Name" => "George",
"Title" => "Watchman",
"Pets" => "Squirtle",
"Spouse" => "Joan",
"Children" => %w[Georgette Georgina]
}
table << { "Name" => "Paulette",
"Title" => "Director",
"Pets" => %w[Feathers Claw IronLion],
"Spouse" => "David",
"Children" => %w[Jules Vern Nemo Nautilus]
}
puts table.to_text
--- text.rb 2010-04-20 16:19:38.949335528 -0400
+++ text.rb.new 2010-04-20 16:24:48.919335633 -0400
@@ -110,16 +110,49 @@
def build_row(data = self.data)
max_col_widths_for_row(data) unless options.max_col_width
- data.enum_for(:each_with_index).inject(line=[]) { |s,e|
- field,index = e
- if options.alignment.eql? :center
- line << field.to_s.center(options.max_col_width[index])
- else
- align = field.is_a?(Numeric) ? :rjust : :ljust
- line << field.to_s.send(align, options.max_col_width[index])
+ # first find any fields in row that contain an array
+ idx = 0
+ max_len = 0
+ array_fields = Array.new # contains indices for field that contain an array
+ data.each do |datum|
+ if datum.class == Array.new.class
+ array_fields.push(idx)
+ max_len = datum.length if datum.length > max_len
end
- }
- output << fit_to_width("| #{line.join(' | ')} |\n")
+ idx += 1
+ end
+
+ # check if data has any cells that contain arrays
+ if array_fields.length != 0
+ 0.upto(max_len-1) do |cnt|
+ data.enum_for(:each_with_index).inject(line=[]) { |s,e|
+ field,index = e
+ if array_fields.include?(index) then
+ # if an array cell, shift next item from array
+ line << field.shift.to_s.send(:ljust, options.max_col_width[index])
+ elsif !array_fields.include?(index) && cnt == 0
+ # if first line of a row and not an array cell, output normally
+ line << field.to_s.send(:ljust, options.max_col_width[index])
+ else
+ # if not the first line of a row, and is not an array cell,
+ # print a blank in the cell
+ line << "".send(:ljust, options.max_col_width[index])
+ end
+ }
+ output << fit_to_width("| #{line.join(' | ')} |\n")
+ end
+ else
+ data.enum_for(:each_with_index).inject(line=[]) { |s,e|
+ field,index = e
+ if options.alignment.eql? :center
+ line << field.to_s.center(options.max_col_width[index])
+ else
+ align = field.is_a?(Numeric) ? :rjust : :ljust
+ line << field.to_s.send(align, options.max_col_width[index])
+ end
+ }
+ output << fit_to_width("| #{line.join(' | ')} |\n")
+ end
end
# Renders the header for a group using the group name.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment