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.



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

def initialize(product, product_params, options = {})
  @product = product || Spree::Product.new(product_params)

  @product_attrs = product_params
  @variants_attrs = options[:variants_attrs] || []
  @options_attrs = options[:options_attrs] || []
end

Instance Attribute Details

#options_attrsObject (readonly)

Returns the value of attribute options_attrs.



5
6
7
# File 'lib/spree/core/importer/product.rb', line 5

def options_attrs
  @options_attrs
end

#productObject (readonly)

Returns the value of attribute product.



5
6
7
# File 'lib/spree/core/importer/product.rb', line 5

def product
  @product
end

#product_attrsObject (readonly)

Returns the value of attribute product_attrs.



5
6
7
# File 'lib/spree/core/importer/product.rb', line 5

def product_attrs
  @product_attrs
end

#variants_attrsObject (readonly)

Returns the value of attribute variants_attrs.



5
6
7
# File 'lib/spree/core/importer/product.rb', line 5

def variants_attrs
  @variants_attrs
end

Instance Method Details

#createObject



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/spree/core/importer/product.rb', line 15

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



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/spree/core/importer/product.rb', line 28

def update
  if product.update_attributes(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_attributes(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