Class: Eco::API::Common::People::DefaultParsers::CSVParser

Inherits:
BaseParser
  • Object
show all
Defined in:
lib/eco/api/common/people/default_parsers/csv_parser.rb

Instance Method Summary collapse

Methods inherited from BaseParser

#initialize

Constructor Details

This class inherits a constructor from Eco::API::Common::People::BaseParser

Instance Method Details

#processObject



8
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
# File 'lib/eco/api/common/people/default_parsers/csv_parser.rb', line 8

def process
  @parsers.define_attribute(:csv, dependencies: @options) do |parser|
    parser.def_parser  do |data, deps|
      arr_hash = []
      CSV.parse(data, headers: true, skip_blanks: true).reject do |row|
        values = row.to_hash.values
        values.all?(&:nil?) || values.map(&:to_s).all?(&:empty?)
      end.each do |row|
        row_hash = row.headers.uniq.each_with_object({}) do |attr, hash|
          value      = row[attr]
          hash[attr] = value.to_s.empty?? nil : value
        end
        arr_hash.push(row_hash)
      end
      arr_hash
    end.def_serializer do |array_hash, deps|
      arr_rows = []
      unless array_hash.empty?
        header = array_hash.first.keys
        arr_rows = array_hash.map do |csv_row|
          CSV::Row.new(header, csv_row.values_at(*header))
        end
      end
      CSV::Table.new(arr_rows).to_csv
    end
  end
end