Created
July 25, 2009 23:49
-
-
Save brandon-beacher/155260 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| require 'fastercsv' | |
| class Importer | |
| def self.import_products(folder) | |
| assets = {} | |
| FasterCSV.foreach("#{folder}/assets.csv") do |row| | |
| assets[row[0]] = row[1] | |
| end | |
| FasterCSV.foreach("#{folder}/products.csv") do |row| | |
| next if row[0] == "Action" | |
| taxonomy = Taxonomy.find_or_create_by_name "Categories" | |
| taxon_names = row[6].split "->" | |
| taxon_names.unshift "Categories" | |
| taxons = [] | |
| parent = nil | |
| taxon_names.each do |taxon_name| | |
| position = parent ? parent.children.count : 0 | |
| taxon = Taxon.find_or_create_by_name :name => taxon_name, :parent => parent, :position => position, :taxonomy => taxonomy | |
| taxons << taxon | |
| parent = taxon | |
| end | |
| product_attributes = { | |
| :description => row[5], | |
| :master_price => row[7], | |
| :name => row[3] } | |
| variant_attributes = { | |
| :depth => row[11], | |
| :height => row[13], | |
| :sku => row[1], | |
| :weight => row[10], | |
| :width => row[12] } | |
| variant = Variant.find_by_sku variant_attributes[:sku] | |
| if variant | |
| product = variant.product | |
| product.attributes = product_attributes | |
| variant.attributes = variant_attributes | |
| product.taxons.replace taxons | |
| puts "updating existing sku #{variant.sku}" | |
| else | |
| product = Product.new product_attributes.merge :available_on => Time.now | |
| variant = product.variants.build variant_attributes.merge(:product => product) | |
| product.taxons << taxons | |
| puts "creating new sku #{variant.sku}" | |
| end | |
| if product.new_record? && File.file?("#{folder}/assets/#{assets[product.sku]}") | |
| product.images.build \ | |
| :attachment => File.new("#{folder}/assets/#{assets[product.sku]}") | |
| end | |
| if product.save && variant.save | |
| puts "saved sku #{variant.sku}" | |
| else | |
| puts "failed to save sku #{variant.sku}" | |
| puts product.errors.full_messages | |
| puts variant.errors.full_messages | |
| raise | |
| end | |
| puts | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment