Class: Spree::Core::Importer::Product

Inherits:
Object
  • Object
show all
Defined in:
lib/spree/core/importer/product.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(product, product_params, options = {}) ⇒ Product

Returns a new instance of Product.



9
10
11
12
13
14
15
# 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

Instance Attribute Details

#options_attrsObject (readonly)

Returns the value of attribute options_attrs.



7
8
9
# File 'lib/spree/core/importer/product.rb', line 7

def options_attrs
  @options_attrs
end

#productObject (readonly)

Returns the value of attribute product.



7
8
9
# File 'lib/spree/core/importer/product.rb', line 7

def product
  @product
end

#product_attrsObject (readonly)

Returns the value of attribute product_attrs.



7
8
9
# File 'lib/spree/core/importer/product.rb', line 7

def product_attrs
  @product_attrs
end

#variants_attrsObject (readonly)

Returns the value of attribute variants_attrs.



7
8
9
# File 'lib/spree/core/importer/product.rb', line 7

def variants_attrs
  @variants_attrs
end

Instance Method Details

#createObject



17
18
19
20
21
22
23
24
25
26
27
28
# 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

#updateObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 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