Created
October 5, 2011 17:21
-
-
Save HeroicEric/1265072 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
class VariantDatasheet < ActiveRecord::Base | |
require 'csv' | |
has_attached_file :csv, :path => ":rails_root/uploads/variant_datasheets/:id/:basename.:extension" | |
validates_attachment_presence :csv | |
def import_data | |
variants = self.get_variants | |
variants.each do |variant_attr| | |
self.make_variant(variant_attr) | |
end | |
end | |
def csv_data | |
CSV.read(self.csv.path) | |
end | |
def headers | |
csv_headers = self.csv_data[0] | |
csv_headers | |
end | |
def variant_data | |
self.csv_data.drop(1) | |
end | |
def get_variants | |
variants = [] | |
self.variant_data.each do |attributes| | |
variants << Hash[self.headers.zip(attributes)] | |
end | |
variants | |
end | |
def get_product(variant_attr) | |
Product.find(variant_attr["product_id"]) | |
end | |
def option_types | |
option_types = ["SKU", "STATUS", "CPU", "SCREEN", "RAM", "HDD", "WLAN/WWLAN", "DRIVE", "OS", "WIRELESS CARRIER", "OTHER"] | |
end | |
def make_variant(variant_attr) | |
product = self.get_product(variant_attr) | |
product.option_types = self.option_types.map do |name| | |
OptionType.find_or_create_by_name_and_presentation(name, name) | |
end | |
variant = Variant.create( | |
:product => product, :sku => variant_attr["SKU"], :price => variant_attr[" SRP "]) | |
variant.option_values = product.option_types.map do |option_type| | |
OptionValue.find_or_create_by_name_and_presentation_and_option_type_id( | |
variant_attr[option_type.name], variant_attr[option_type.name], option_type.id) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment