Sha256: ce98b83838e60eacf2788c592df2cbe4835321a416276bc774ccd011fcb3e90f

Contents?: true

Size: 1.14 KB

Versions: 6

Compression:

Stored size: 1.14 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

    def populate(variant_id, quantity, options = {})
      # protect against passing a nil hash being passed in
      # due to an empty params[:options]
      attempt_cart_add(variant_id, quantity, options || {})
      valid?
    end

    def valid?
      errors.empty?
    end

    private

    def attempt_cart_add(variant_id, quantity, options = {})
      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, options.merge(currency: currency))
        unless line_item.valid?
          errors.add(:base, line_item.errors.messages.values.join(" "))
          return false
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
spree_core-2.4.2 app/models/spree/order_populator.rb
spree_core-2.4.1 app/models/spree/order_populator.rb
spree_core-2.4.0 app/models/spree/order_populator.rb
spree_core-2.4.0.rc3 app/models/spree/order_populator.rb
spree_core-2.4.0.rc2 app/models/spree/order_populator.rb
spree_core-2.4.0.rc1 app/models/spree/order_populator.rb