Class: Ahnnotate::Function::Tabularize
- Inherits:
-
Object
- Object
- Ahnnotate::Function::Tabularize
- Defined in:
- lib/ahnnotate/function/tabularize.rb
Instance Method Summary collapse
- #call(data, column_names) ⇒ Object
-
#initialize(prefix:, cell_divider:) ⇒ Tabularize
constructor
A new instance of Tabularize.
Constructor Details
#initialize(prefix:, cell_divider:) ⇒ Tabularize
Returns a new instance of Tabularize.
4 5 6 7 |
# File 'lib/ahnnotate/function/tabularize.rb', line 4 def initialize(prefix:, cell_divider:) @prefix = prefix @cell_divider = cell_divider end |
Instance Method Details
#call(data, column_names) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/ahnnotate/function/tabularize.rb', line 9 def call(data, column_names) output = StringIO.new minimum_column_lengths = Hash.new { 0 } rows = data.map do |row| row_hash = {} column_names.each do |c| value = row.public_send(c).to_s row_hash[c] = value if value.size > minimum_column_lengths[c] minimum_column_lengths[c] = value.size end end row_hash end rows.each do |row| # Note: minimum_column_lengths shouldn't include any of the columns # with a length of zero since they were never explicitly set (to 0) minimum_column_lengths.each.with_index do |(column_name, column_max_length), index| if index == 0 output.print(@prefix) end if_rightmost_column = index + 1 == minimum_column_lengths.size if if_rightmost_column output.puts "#{row[column_name]}" else column_length = row[column_name].size spaces_length = column_max_length - column_length output.print "#{row[column_name]}#{" " * spaces_length}#{@cell_divider}" end end end output.string.gsub(/ +$/, "") end |