Skip to content

Instantly share code, notes, and snippets.

@phillyslick
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phillyslick/10428490 to your computer and use it in GitHub Desktop.
Save phillyslick/10428490 to your computer and use it in GitHub Desktop.
## Importing Data from CSV to Rails psql
## Code is essentially ripped from:
## here: http://stackoverflow.com/questions/14534522/ruby-csv-parsing-string-with-escaped-quotes (thanks!)
## and here: http://technicalpickles.com/posts/parsing-csv-with-ruby/ (double thanks!)
## using Sequel Pro for OSX to tear up / navigat the murkey waters of a Wordpress Database
csv_data = File.read('data.csv').gsub(/\\"/,'""')
csv = CSV.new(csv_data, {headers: true})
arrayed_csv = csv.to_a
hashed_csv_with_blank_strings = CSV.new(csv_data, :headers => true, :header_converters => :symbol, :converters => :all)
hashed_csv_with_blank_strings.to_a.map {|row| row.to_hash }
# or if you prefer nil values rather than empty strings
CSV::Converters[:blank_to_nil] = lambda do |field|
field && field.empty? ? nil : field
end
csv = CSV.new(csv_data, :headers => true, :header_converters => :symbol, :converters => [:all, :blank_to_nil])
csv_map = csv.to_a.map {|row| row.to_hash }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment