Module: S3MPI::Converters::CSV

Extended by:
CSV
Included in:
CSV
Defined in:
lib/s3mpi/converters/csv.rb

Defined Under Namespace

Classes: HeaderError

Instance Method Summary collapse

Instance Method Details

#generate(array_of_hashes, options = Hash.new) ⇒ String

Convert an array of hashes to CSV string data

Parameters:

  • array_of_hashes (Array)

    An Array of Hashes

  • options (Hash) (defaults to: Hash.new)

    Passed to CSV.generate

Returns:

  • (String)


36
37
38
39
40
41
42
43
44
45
# File 'lib/s3mpi/converters/csv.rb', line 36

def generate(array_of_hashes, options = Hash.new)
  return "" if array_of_hashes.empty?
  headers = inspect_headers(array_of_hashes)
  ::CSV.generate(options) do |csv|
    csv << headers
    array_of_hashes.each do |hash|
      csv << hash.values_at(*headers)
    end
  end
end

#parse(csv_data, options = Hash.new) ⇒ Array

Convert CSV string data to an array of hashes

Parameters:

  • csv_data (String)

    String of CSV data

  • options (Hash) (defaults to: Hash.new)

    Passed to CSV.parse

Returns:

  • (Array)


19
20
21
22
23
24
25
# File 'lib/s3mpi/converters/csv.rb', line 19

def parse(csv_data, options = Hash.new)
  options = options.merge({
                            headers:    true,
                            converters: :all
                          })
  ::CSV.parse(csv_data, options).map(&:to_hash)
end