Sha256: 71bea35a643df130def0778d414baf27857a5ce2a24bf273f278659aff739007

Contents?: true

Size: 1.63 KB

Versions: 15

Compression:

Stored size: 1.63 KB

Contents

module Spree
  class ProductDuplicator
    attr_accessor :product

    def initialize(product)
      @product = product
    end

    def duplicate
      new_product = duplicate_product

      # don't dup the actual variants, just the characterising types
      new_product.option_types = product.option_types if product.has_variants?

      # allow site to do some customization
      new_product.send(:duplicate_extra, product) if new_product.respond_to?(:duplicate_extra)
      new_product.save!
      new_product
    end

    protected

    def duplicate_product
      product.dup.tap do |new_product|
        new_product.name = "COPY OF #{product.name}"
        new_product.taxons = product.taxons
        new_product.created_at = nil
        new_product.deleted_at = nil
        new_product.updated_at = nil
        new_product.product_properties = reset_properties
        new_product.master = duplicate_master
      end
    end

    def duplicate_master
      master = product.master
      master.dup.tap do |new_master|
        new_master.sku = "COPY OF #{master.sku}"
        new_master.deleted_at = nil
        new_master.images = master.images.map { |image| duplicate_image image }
        new_master.price = master.price
        new_master.currency = master.currency
      end
    end

    def duplicate_image(image)
      new_image = image.dup
      new_image.assign_attributes(:attachment => image.attachment.clone)
      new_image
    end

    def reset_properties
      product.product_properties.map do |prop|
        prop.dup.tap do |new_prop|
          new_prop.created_at = nil
          new_prop.updated_at = nil
        end
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
spree_core-2.1.4 lib/spree/core/product_duplicator.rb
spree_core-2.0.8 lib/spree/core/product_duplicator.rb
spree_core-2.1.3 lib/spree/core/product_duplicator.rb
spree_core-2.0.7 lib/spree/core/product_duplicator.rb
spree_core-2.1.2 lib/spree/core/product_duplicator.rb
spree_core-2.0.6 lib/spree/core/product_duplicator.rb
spree_core-2.1.1 lib/spree/core/product_duplicator.rb
spree_core-2.0.5 lib/spree/core/product_duplicator.rb
spree_core-2.1.0 lib/spree/core/product_duplicator.rb
spree_core-2.0.4 lib/spree/core/product_duplicator.rb
spree_core-2.0.3 lib/spree/core/product_duplicator.rb
spree_core-2.0.2 lib/spree/core/product_duplicator.rb
spree_core-2.0.1 lib/spree/core/product_duplicator.rb
spree_core-2.0.0 lib/spree/core/product_duplicator.rb
spree_core-2.0.0.rc1 lib/spree/core/product_duplicator.rb