Last active
August 29, 2015 13:58
-
-
Save phillyslick/10428490 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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