Skip to content

Instantly share code, notes, and snippets.

@TylerRick
Forked from BDQ/Import
Created March 7, 2012 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TylerRick/1996785 to your computer and use it in GitHub Desktop.
Save TylerRick/1996785 to your computer and use it in GitHub Desktop.
namespace :spree do
desc "Export Products to CSV File"
task :export_products => :environment do
require 'csv'
products = Product.where(:deleted_at => nil).all
puts "Exporting to #{RAILS_ROOT}/products.csv"
CSV.open("#{RAILS_ROOT}/products.csv", "w") do |csv|
csv << [
"id",
"sku",
"name",
"description",
"price",
"weight"
]
products.each do |p|
csv << [
p.id,
p.sku,
p.name.titleize,
p.description,
p.price.to_s,
p.weight.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 'csv'
n = 0
u = 0
CSV.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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment