class Spree::Core::Importer::Product

Attributes

options_attrs[R]
product[R]
product_attrs[R]
variants_attrs[R]

Public Class Methods

new(product, product_params, options = {}) click to toggle source
# File lib/spree/core/importer/product.rb, line 9
def initialize(product, product_params, options = {})
  @product = product || Spree::Product.new(product_params)

  @product_attrs = product_params.to_h
  @variants_attrs = (options[:variants_attrs] || []).map(&:to_h)
  @options_attrs = options[:options_attrs] || []
end

Public Instance Methods

create() click to toggle source
# File lib/spree/core/importer/product.rb, line 17
def create
  if product.save
    variants_attrs.each do |variant_attribute|
      # make sure the product is assigned before the options=
      product.variants.create({ product: product }.merge(variant_attribute))
    end

    set_up_options
  end

  product
end
update() click to toggle source
# File lib/spree/core/importer/product.rb, line 30
def update
  if product.update(product_attrs)
    variants_attrs.each do |variant_attribute|
      # update the variant if the id is present in the payload
      if variant_attribute['id'].present?
        product.variants.find(variant_attribute['id'].to_i).update(variant_attribute)
      else
        # make sure the product is assigned before the options=
        product.variants.create({ product: product }.merge(variant_attribute))
      end
    end

    set_up_options
  end

  product
end

Private Instance Methods

set_up_options() click to toggle source
# File lib/spree/core/importer/product.rb, line 50
def set_up_options
  options_attrs.each do |name|
    option_type = Spree::OptionType.where(name: name).first_or_initialize do |ot|
      ot.presentation = name
      ot.save!
    end

    unless product.option_types.include?(option_type)
      product.option_types << option_type
    end
  end
end