Sha256: 34b7115e971b788dcee9f390955b75add43a9887be40f8f894deb7ba96db6be8

Contents?: true

Size: 796 Bytes

Versions: 3

Compression:

Stored size: 796 Bytes

Contents

require 'csv'

module Executrix
  module Helper
    extend self

    CSV_OPTIONS = {
      col_sep: ',',
      quote_char: '"',
      force_quotes: true,
    }

    def records_to_csv records
      file_mock = StringIO.new
      csv_client = CSV.new(file_mock, CSV_OPTIONS)
      all_headers = []
      all_rows = []
      records.each do |hash|
        row = CSV::Row.new([],[],false)
        to_store = hash.inject({}) do |h, (k, v)|
          h[k] = v.class == Array ? v.join(';') : v
          h
        end
        row << to_store
        all_headers << row.headers
        all_rows << row
      end
      all_headers.flatten!.uniq!
      csv_client << all_headers
      all_rows.each do |row|
        csv_client << row.fields(*all_headers)
      end
      file_mock.string
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
executrix-1.1.1 lib/executrix/helper.rb
executrix-1.1.0 lib/executrix/helper.rb
executrix-1.0.0 lib/executrix/helper.rb