Sha256: 8c4da24c4b945c0a63fc1e3d4215ba523287ab94584f328a140f3cba29454e3c

Contents?: true

Size: 725 Bytes

Versions: 10

Compression:

Stored size: 725 Bytes

Contents

require 'csv'

class CsvSerializer
  def self.load(csv_string)
    # takes a CSV string, and returns an Array of Hashes
    # the keys are the column names and the values are the values.
    # keys and values will all be strings.

    csv_table = CSV.parse(csv_string.present? ? csv_string : '', headers: :first_row)
    csv_table.map { |csv_row| csv_row.to_hash }
  end

  def self.dump(data)
    # takes something that behaves like an Array of Hashes, and returns a CSV string.

    headers = data.try(:first).present? ? data.first.keys : []
    CSV.generate(headers: headers, write_headers: true) do |csv|
      data.try(:map) do |data_hash|
        csv << headers.map { |key| data_hash[key] }
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
aleph_analytics-0.3.0 lib/csv_serializer.rb
aleph_analytics-0.2.0 lib/csv_serializer.rb
aleph_analytics-0.1.0 lib/csv_serializer.rb
aleph_analytics-0.0.6 lib/csv_serializer.rb
aleph_analytics-0.0.5 lib/csv_serializer.rb
aleph_analytics-0.0.4 lib/csv_serializer.rb
aleph_analytics-0.0.3 lib/csv_serializer.rb
aleph_analytics-0.0.2 lib/csv_serializer.rb
aleph_analytics-0.0.1.alpha lib/csv_serializer.rb
aleph_analytics-0.0.0.alpha lib/csv_serializer.rb