Skip to content

@andywenk /import-example.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
csv-import-example
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.