Skip to content

Instantly share code, notes, and snippets.

@wemerson
Created October 17, 2009 18:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wemerson/212429 to your computer and use it in GitHub Desktop.
Save wemerson/212429 to your computer and use it in GitHub Desktop.
Spree Variant Uploads
class Admin::VariantsController < Admin::BaseController
...
#add this to controllers/admin/variants_controller.rb or override in extension
#update directory must exist
UPDATE_DIRECTORY = 'public/updates'
require 'fastercsv'
def variants_csv_import
file = params[:dump][:file]
csv_import(file, "variants")
end
def csv_import(file, table_name)
#working on making this generic, so will work with any model but having problems with table objects.
#for now, must specify model in code below, substitute model name for Variant
#mymodel = table_name.classify.constantize
t = Time.now
filepath = File.join(UPDATE_DIRECTORY, t.strftime("%Y%m%d%H%M%S") + ".txt")
if file.is_a? StringIO
File.open(filepath, File::RDWR|File::CREAT) { |f| f << file.read }
else
FileUtils.cp(file.path, filepath)
end
#set for tab-delimited, for csv use :col_sep => "\c"
#first line of import file must contain correct field names separated by delimiters
#does not need all fields and order doesn't matter except for key.
n = 0
u = 0
FCSV.foreach(filepath,
:col_sep => "\t",
:headers => true,
:header_converters => :symbol ) do |line|
row = line.to_hash
#key must be specified
#sku must be key in this system--it's second field
key = line[1]
@item = Variant.find_by_sku(key)
if @item
row.merge({"id" => @item.id})
@item.update_attributes(row)
u = u + 1
else
@item = Variant.new
row.merge({"id" => @item.id})
@item = Variant.create(row)
n = n + 1
end
end
#add error handling
flash[:notice]="CSV Import Successful. #{n}records created, #{u} records updated."
redirect_to :controller => 'admin/products', :action => 'index'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment