public
Last active

  • Download Gist
Spree Export/Import
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
namespace :spree do
desc "Export Products to CSV File"
task :export_products => :environment do
require 'fastercsv'
 
products = Product.find(:all)
puts "Exporting to #{RAILS_ROOT}/products.csv"
FasterCSV.open("#{RAILS_ROOT}/products.csv", "w") do |csv|
csv << ["id", "name", "description","sku", "master_price" ]
 
products.each do |p|
csv << [p.id,
p.name.titleize,
p.description,
p.sku,
p.master_price.to_s]
end
end
 
puts "Export Complete"
end
desc "Update / Import products from CSV File, expects file=/path/to/import.csv"
task :import_products => :environment do
require 'fastercsv'
n = 0
u = 0
FasterCSV.foreach(ENV['file']) do |row|
if row[0].nil?
# Adding new product
puts "Adding new product: #{row[1]}"
product = Product.new()
n += 1
else
# Updating existing product
next if row[0].downcase == "id" #skip header row
puts "Updating product: #{row[1]}"
product = Product.find(row[0])
u += 1
end
product.name = row[1]
product.description = row[2]
product.sku = row[3].to_s
product.master_price = row[4].to_d
product.save!
end
puts ""
puts "Import Completed - Added: #{n} | Updated #{u} Products"
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.