Class: ADSL::Util::CSVHashFormatter
- Defined in:
- lib/adsl/util/csv_hash_formatter.rb
Instance Method Summary collapse
- #add_column(col) ⇒ Object
- #add_row(row) ⇒ Object (also: #<<)
- #column_type(col) ⇒ Object
- #escape_str(obj) ⇒ Object
- #infer_column_types ⇒ Object
-
#initialize(*cols) ⇒ CSVHashFormatter
constructor
A new instance of CSVHashFormatter.
- #prepare_for_csv(row) ⇒ Object
- #sort!(*columns) ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(*cols) ⇒ CSVHashFormatter
Returns a new instance of CSVHashFormatter.
17 18 19 20 21 22 23 |
# 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 |
Instance Method Details
#add_column(col) ⇒ Object
39 40 41 42 |
# 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) ⇒ Object Also known as: <<
31 32 33 34 35 36 37 |
# 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 |
#column_type(col) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 |
# 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) ⇒ Object
13 14 15 |
# File 'lib/adsl/util/csv_hash_formatter.rb', line 13 def escape_str(obj) "\"#{obj.to_s.gsub('"', '""')}\"" end |
#infer_column_types ⇒ Object
59 60 61 62 63 64 65 |
# 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) ⇒ Object
25 26 27 28 29 |
# 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) ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# 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 ⇒ Object
83 84 85 86 87 88 89 90 91 |
# 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 |