Skip to content

Instantly share code, notes, and snippets.

@ikraamg
Forked from cesartalves/script.rb
Last active July 1, 2021 11:05
Show Gist options
  • Save ikraamg/d2d1d95486121ff9ec360300448d6186 to your computer and use it in GitHub Desktop.
Save ikraamg/d2d1d95486121ff9ec360300448d6186 to your computer and use it in GitHub Desktop.
Import option value to products for `Cans` option_type
cans = Spree::OptionType.find_by!(name: "quantity")
one = Spree::OptionValue.find_by!(name: "quantity-1")
three = Spree::OptionValue.find_by!(name: "quantity-3")
six = Spree::OptionValue.find_by!(name: "quantity-6")
twelve = Spree::OptionValue.find_by!(name: "quantity-12")
twenty_four = Spree::OptionValue.find_by!(name: "quantity-24")
option_value_hash = {
"1" => one,
"3" => three,
"6" => six,
"12" => twelve,
"24" => twenty_four
}
failed_variants = []
variants = []
csv = CSV.read('Legacy SKUs.csv', headers: true)
csv.each do |context|
variant = Spree::Variant.find_by(sku: context['Legacy SKU'])
# Ensure that variant is master because legacy orders were imported with only a master variant
if variant.nil? || !variant.is_master
failed_variants << variant
next
end
# Add option type if not included
product_option_types = variant.product.option_types
product_option_types << cans unless product_option_types.include? cans
# Add option value if not included
quanitity = option_value_hash[context['Quantity']]
variant.option_values << quanitity unless variant.option_values.include? quanitity
variants << variant
end
puts "Affected:", variants.size
puts "Failed: ", failed_variants.size
####################################
# Local testing of the script (by adding local SKU to the CSV file)
cans = Spree::OptionType.first
one = Spree::OptionValue.first
three = Spree::OptionValue.second
six = Spree::OptionValue.third
twelve = Spree::OptionValue.fourth
twenty_four = Spree::OptionValue.fifth
option_value_hash = {
"1" => one,
"3" => three,
"6" => six,
"12" => twelve,
"24" => twenty_four
}
variants = []
failed_variants = []
csv = CSV.read('Legacy SKUs.csv', headers: true)
csv.each do |context|
variant = Spree::Variant.find_by(sku: context['Legacy SKU'])
# Ensure that variant is master because legacy orders were imported with only a master variant
if variant.nil? || !variant.is_master
failed_variants << variant
next
end
# Add option type if not included
product_option_types = variant.product.option_types
product_option_types << cans unless product_option_types.include? cans
# Add option value if not included
quanitity = option_value_hash[context['Quantity']]
variant.option_values << quanitity unless variant.option_values.include? quanitity
variants << variant
end
puts "Affected:", variants.size
puts "Failed: ", failed_variants.size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment