Sha256: ad6c6e111d5f648b51e132c9dde868f05e223dd9dba2501747a5df657bcf05e6

Contents?: true

Size: 1.53 KB

Versions: 23

Compression:

Stored size: 1.53 KB

Contents

module Spree
  class OrderPopulator
    attr_accessor :order, :currency
    attr_reader :errors

    def initialize(order, currency)
      @order = order
      @currency = currency
      @errors = ActiveModel::Errors.new(self)
    end

    #
    # Parameters can be passed using the following possible parameter configurations:
    #
    # * Single variant/quantity pairing
    # +:variants => { variant_id => quantity }+
    #
    # * Multiple products at once
    # +:products => { product_id => variant_id, product_id => variant_id }, :quantity => quantity+
    def populate(from_hash)
      from_hash[:products].each do |product_id,variant_id|
        attempt_cart_add(variant_id, from_hash[:quantity])
      end if from_hash[:products]

      from_hash[:variants].each do |variant_id, quantity|
        attempt_cart_add(variant_id, quantity)
      end if from_hash[:variants]

      valid?
    end

    def valid?
      errors.empty?
    end

    private

    def attempt_cart_add(variant_id, quantity)
      quantity = quantity.to_i
      # 2,147,483,647 is crazy.
      # See issue #2695.
      if quantity > 2_147_483_647
        errors.add(:base, Spree.t(:please_enter_reasonable_quantity, :scope => :order_populator))
        return false
      end

      variant = Spree::Variant.find(variant_id)
      if quantity > 0
        line_item = @order.contents.add(variant, quantity, currency)
        unless line_item.valid?
          errors.add(:base, line_item.errors.messages.values.join(" "))
          return false
        end
      end
    end
  end
end

Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
spree_core-2.1.12 app/models/spree/order_populator.rb
spree_core-2.1.11 app/models/spree/order_populator.rb
spree_core-2.1.10 app/models/spree/order_populator.rb
spree_core-2.0.13 app/models/spree/order_populator.rb
spree_core-2.1.9 app/models/spree/order_populator.rb
spree_core-2.1.8 app/models/spree/order_populator.rb
spree_core-2.0.12 app/models/spree/order_populator.rb
spree_core-2.1.7 app/models/spree/order_populator.rb
spree_core-2.0.11 app/models/spree/order_populator.rb
spree_core-2.0.10 app/models/spree/order_populator.rb
spree_core-2.1.6 app/models/spree/order_populator.rb
spree_core-2.1.5 app/models/spree/order_populator.rb
spree_core-2.0.9 app/models/spree/order_populator.rb
spree_core-2.1.4 app/models/spree/order_populator.rb
spree_core-2.0.8 app/models/spree/order_populator.rb
spree_core-2.1.3 app/models/spree/order_populator.rb
spree_core-2.0.7 app/models/spree/order_populator.rb
spree_core-2.1.2 app/models/spree/order_populator.rb
spree_core-2.0.6 app/models/spree/order_populator.rb
spree_core-2.1.1 app/models/spree/order_populator.rb