Skip to content

Instantly share code, notes, and snippets.

@jonpaul
Created October 10, 2011 17:22
Show Gist options
  • Save jonpaul/1275851 to your computer and use it in GitHub Desktop.
Save jonpaul/1275851 to your computer and use it in GitHub Desktop.
require 'csv'
class ListingsController < ApplicationController
before_filter :login_required, :except => [:show, :index]
def index
@listings = session[:map_fields][:mapped_headers]
end
def new
@listing = Listing.new
end
def create
@import_headers = params[:listing]
if @import_headers.has_value?("" || nil)
redirect_to :action => 'new', :alert => "Please resubmit your mapping and ensure all fields have been paired."
else
CSV.foreach(session[:map_fields][:file], { :headers => true, :return_headers => false}) do |row|
@listing = Listing.new(:product_type => @import_headers["product_type"], :user_id => current_user.id, :organization_id => current_user.company.try(:id) || current_user.organization.id, :listing_name => @import_headers["listing_name"])
count = 0
@import_headers.each_pair { |key, header|
unless header.blank? || key == "product_type" || key == "listing_name"
@listing.write_attribute(header.to_sym, row[count])
count += 1
end
}
@listing.save
end
@import_headers.each_pair { |key, value|
MdmField.all.each { |o|
o.mdm_alternatives.find_or_create_by_header(key) if o.header == value
}
}
session[:map_fields] = nil
redirect_to root_path, :notice => "Your data has been processed and uploaded."
end
end
def map_listing
#TODO: Clean up the dropdowns eventually
@mdm_defaults = MdmField.all.collect { |f| f.header.downcase.tr(" ", "_").delete("^a-z0-9_").to_sym }
@mdm_headers = MdmField.all
@mdm_alts = MdmAlternative.all
@mdm_unsafe = Mongoid.destructive_fields.collect { |h| h.to_s } + ["class", "type"]
if params[:map_listing][:file]
file_field = params[:map_listing][:file]
session[:map_fields] = {}
temp_path = File.join(Dir::tmpdir, "map_fields_#{Time.now.to_i}_#{$$}")
File.open(temp_path, 'wb') do |f|
f.write file_field.read
end
session[:map_fields][:file] = temp_path
end
CSV.foreach(session[:map_fields][:file], { :headers => true, :return_headers => true }) do |row|
@import_headers = row if row.header_row?
end
new_array = []
@import_headers.to_hash.each_key {|k| new_array << k}
@import_headers = new_array.compact!.collect {|h| h.downcase.tr(" ", "_").delete("^a-z0-9_").to_sym}
render
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment