class ADSL::Util::CSVHashFormatter
Public Class Methods
new(*cols)
click to toggle source
# File lib/adsl/util/csv_hash_formatter.rb, line 17 def initialize(*cols) @row_hashes = [] @columns = [] cols.each do |col| add_column col end end
Public Instance Methods
add_column(col)
click to toggle source
# File lib/adsl/util/csv_hash_formatter.rb, line 39 def add_column(col) raise "Duplicate column name #{col}" if @columns.include? col.to_sym @columns << col.to_sym end
add_row(row)
click to toggle source
# File lib/adsl/util/csv_hash_formatter.rb, line 31 def add_row(row) prepare_for_csv row @row_hashes << row row.keys.each do |key| add_column key unless @columns.include? key end end
Also aliased as: <<
column_type(col)
click to toggle source
# File lib/adsl/util/csv_hash_formatter.rb, line 46 def column_type(col) type = nil @row_hashes.each do |row| next if row[col].nil? if row[col].is_a?(Numeric) && type.nil? type = Numeric elsif row[col].is_a?(String) || row[col].is_a?(Symbol) type = String end end type end
escape_str(obj)
click to toggle source
# File lib/adsl/util/csv_hash_formatter.rb, line 13 def escape_str(obj) "\"#{obj.to_s.gsub('"', '""')}\"" end
infer_column_types()
click to toggle source
# File lib/adsl/util/csv_hash_formatter.rb, line 59 def infer_column_types types = {} @columns.each do |col| types[col] = column_type col end types end
prepare_for_csv(row)
click to toggle source
# File lib/adsl/util/csv_hash_formatter.rb, line 25 def prepare_for_csv(row) row.keys.each do |col| row[col] = row[col].to_s if row[col].is_a? Symbol end end
sort!(*columns)
click to toggle source
# File lib/adsl/util/csv_hash_formatter.rb, line 67 def sort!(*columns) types = infer_column_types @row_hashes.sort_by! do |row| columns.map do |col| if types[col] == nil nil elsif types[col] == Numeric row[col] || -Float::INFINITY else row[col] || '' end end.to_a end self end
to_s()
click to toggle source
# File lib/adsl/util/csv_hash_formatter.rb, line 83 def to_s return '' if @columns.empty? output = @columns.map{ |c| escape_str(c) }.join(',') + "\n" types = infer_column_types @row_hashes.each do |row| output += @columns.map{ |c| types[c] == Numeric ? (row[c] || '') : escape_str(row[c] || '') }.join(',') + "\n" end output end