public
Last active

csv-import-example

  • Download Gist
import-example.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
# This is a basic example how to create an import from csv data. This could
# be called in a rake task:
 
namespace :db do
namespace :import do
desc "Import customer of old shop from csv"
task :customer => :environment do
csv_file = 'db/customer_data.csv'
importer = Import::ImportCustomer.new(IO.read(csv_file))
importer.import
end
end
end
 
# Here is a basic import module and class and a class for a userImport - this should
# be placed in two separate files.
# I removed the error handling from the code to concentrate more on the basics. I
# strongly recommend to add it!
 
require 'csv'
 
module Import
class Importer
attr_accessor :csv_stream
 
def initialize(csv_stream)
@csv_data = {}
convert_csv_data(csv_stream)
end
 
def convert_csv_data(csv_stream)
@csv_data = CSV.new csv_stream, {:headers => true, :col_sep => ','}
@csv_data.convert do |field, info|
next if field.blank?
field.strip
end
end
end
 
module Import
class ImportCustomer < Importer
def import
User.transaction do
import_customer_data
end
end
 
def import_customer_data
@csv_data.each do |row|
data = row.to_hash
save_data_to_db(data)
end
end
 
def save_data_to_db(data)
data_hash = {
:email => data['kd_email'] || '',
:salutation => data['kd_anrede'] || '',
:first_name => data['kd_vorname'] || '',
:last_name => data['kd_nachname'] || ''
}
 
user = User.new(data_hash)
user.save
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.