Import a CSV file

Public, Ruby General

harrylevine

Created: Feb 17, 2019     Updated: Feb 17, 2019


This is a simple implementation that uses Ruby's CSV class to:

# csv_importer.rb

require 'csv'
require 'ostruct'

class CsvImporter
  # @return [OpenStruct] Sample:
  #   OpenStruct {
  #     :data => [
  #       {
  #         :id         => "1",
  #         :first_name => "Lynne",
  #         :last_name  => "Vennings",
  #         :email      => "lvennings0@ftc.gov",
  #         :gender     => "Female",
  #         :ip_address => "203.27.47.29"
  #       },
  #       ...
  #     ]
  #   }
  #
  def self.import(path)
    results = OpenStruct.new(data: [])

    CSV.foreach(path, headers: true, header_converters: :symbol) do |row|
      results.data << row.to_hash
    end

    results
  end
end