Module: AdHocTemplate::RecordReader::CSVReader

Defined in:
lib/ad_hoc_template/record_reader.rb

Class Method Summary collapse

Class Method Details

.parse_config(config) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ad_hoc_template/record_reader.rb', line 54

def self.parse_config(config)
  case config
  when Symbol
    format, label = config, nil
  when String
    format, label = :csv, config
  when Hash
    format, label = config.to_a[0]
  end
  field_sep = format == :tsv ? "\t" : CSV::DEFAULT_OPTIONS[:col_sep]
  return label, field_sep
end

.read_record(csv_data, config = { csv: nil }) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ad_hoc_template/record_reader.rb', line 32

def self.read_record(csv_data, config={ csv: nil })
  label, sep  = parse_config(config)
  header, *data = CSV.new(csv_data, col_sep: sep).to_a
  records = data.map {|row| convert_to_hash(header, row) }
  if label
    { '#' + label => records }
  elsif records.length == 1
    records[0]
  else
    records
  end
end