Class: ExoBasic::CSV
- Inherits:
-
Object
- Object
- ExoBasic::CSV
- Defined in:
- lib/exobasic/data/csv.rb
Class Method Summary collapse
- .append_file_info(rec, filename, line) ⇒ Object
- .load_csv_file_as_hash(csv_file, tok_char = ',', with_file_info = false) ⇒ Object
- .load_csv_file_as_list(csv_file, tok_char = ',', with_file_info = false) ⇒ Object
- .mk_hdr(elements) ⇒ Object
- .mk_rec(hdr, elements) ⇒ Object
- .str_tok(str, tok_char) ⇒ Object
Class Method Details
.append_file_info(rec, filename, line) ⇒ Object
25 26 27 28 |
# File 'lib/exobasic/data/csv.rb', line 25 def self.append_file_info(rec, filename, line) rec['file'] = filename rec['line_no'] = line + 1 end |
.load_csv_file_as_hash(csv_file, tok_char = ',', with_file_info = false) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/exobasic/data/csv.rb', line 51 def self.load_csv_file_as_hash(csv_file, tok_char=',', with_file_info=false) fields = [] records = {} File.foreach(csv_file).with_index do |line, line_num| pieces = CSV.str_tok(line, tok_char) if line_num == 0 fields = CSV.mk_hdr(pieces) else record = CSV.mk_rec(fields, pieces) record['id'] = pieces[0] if with_file_info CSV.append_file_info(record, csv_file, line_num) end records[record['id']] = record end end records end |
.load_csv_file_as_list(csv_file, tok_char = ',', with_file_info = false) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/exobasic/data/csv.rb', line 30 def self.load_csv_file_as_list(csv_file, tok_char=',', with_file_info=false) fields = [] records = [] File.foreach(csv_file).with_index do |line, line_num| pieces = CSV.str_tok(line, tok_char) if line_num == 0 fields = CSV.mk_hdr(pieces) else record = CSV.mk_rec(fields, pieces) if with_file_info CSV.append_file_info(record, csv_file, line_num) end records.push(record) end end records end |
.mk_hdr(elements) ⇒ Object
7 8 9 |
# File 'lib/exobasic/data/csv.rb', line 7 def self.mk_hdr(elements) elements.map { |i| i.downcase } end |
.mk_rec(hdr, elements) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/exobasic/data/csv.rb', line 11 def self.mk_rec(hdr, elements) hdr.zip(elements) .map do |pair| k = pair[0] v = pair[1] if !v.nil? v = v.strip end [k, v] end .to_h end |
.str_tok(str, tok_char) ⇒ Object
3 4 5 |
# File 'lib/exobasic/data/csv.rb', line 3 def self.str_tok(str, tok_char) str.strip.split(tok_char) end |