Skip to content

Instantly share code, notes, and snippets.

@ronzalo
Created June 3, 2015 18:14
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 ronzalo/27b01228ac13f2b7e3d8 to your computer and use it in GitHub Desktop.
Save ronzalo/27b01228ac13f2b7e3d8 to your computer and use it in GitHub Desktop.
Taxon importer for spree_importer_core
class Spree::TaxonImporter < Spree::ImporterCore::BaseImporter
# Load a file and the get data from each file row
#
# @params
# row => "Hombre > Vestuario > Chaquetas > Parkas"
def load_data(row:)
return unless row[0].present?
taxons = row[0].split(">").map!(&:strip)
process_taxons(taxons)
end
# Recibe un array de strings ["Hombre", "Vestuario", "Chaquetas"] y crea un arbol jerarquico
# en base a la posición en el array
# See https://github.com/collectiveidea/awesome_nested_set/wiki/Awesome-nested-set-cheat-sheet
def process_taxons(taxons)
taxon_hash = {}
taxonomy = nil
taxons.each_with_index do |t, index|
if index == 0
taxonomy = Spree::Taxonomy.find_or_create_by! name: t
taxon_hash[index] = taxonomy.root
else
taxon = Spree::Taxon.find_or_create_by!({name: t, taxonomy: taxonomy})
taxon.move_to_child_of(taxon_hash[index-1])
taxon_hash[index] = taxon
end
end
taxonomy.reload if taxonomy
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment