Sha256: 8cf9eb57056da9f100f4ed6f5a7db14c1f853ec1c768abfbc3c4eb0aabad54b8

Contents?: true

Size: 1.71 KB

Versions: 7

Compression:

Stored size: 1.71 KB

Contents

module TbCheckout
  class Cart < ActiveRecord::Base
    self.table_name = 'tb_checkout_carts'
    has_many :cart_items, :inverse_of => :cart
    has_many :transactions, :inverse_of => :cart

    scope :completed, ->{ where(:is_completed => true) }
    scope :in_progress, ->{ where(:is_completed => false, :is_abandoned => false) }
    scope :abandoned, ->{ where(:is_abandoned => true) }

    include TbCheckout::BelongsToUserSession

    # Look for carts that have outlived the configured TbCheckout.config.cart_lifespan value and mark them as abandoned
    #
    def self.check_abandoned!
      carts = in_progress.where('updated_at < ?', DateTime.now - TbCheckout.config.cart_lifespan)
      return carts.update_all(:is_abandoned => true)
    end

    # Build a short description of the cart contents
    #
    def description
      if cart_items.length == 0
        desc = "This cart is currently empty"
      elsif cart_items.length > 1
        desc = "#{cart_items.first.item_description} and #{cart_items.length-1} other #{'item'.pluralize(cart_items.length-1)}"
      else
        desc = cart_items.first.item_description
      end
      return desc
    end

    def total_price
      return self.cart_items.collect(&:total_price).sum()
    end

    def add_to_cart(product, quantity: 1)
      if !product.class.included_modules.map(&:to_s).include?("TbCheckout::Purchasable")
        raise ArgumentError, 'product must conform to TbCheckout::Purchasable'
      end
      return self.cart_items.create({
        :item => product,
        :quantity => quantity
      })
    end

    def is_empty?
      return self.cart_items.count == 0
    end

    def user_full_name
      return self.spud_user.try(:full_name) || 'Anonymous'
    end

  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
tb_checkout-1.1.1 app/models/tb_checkout/cart.rb
tb_checkout-1.1.0 app/models/tb_checkout/cart.rb
tb_checkout-1.0.7 app/models/tb_checkout/cart.rb
tb_checkout-1.0.6 app/models/tb_checkout/cart.rb
tb_checkout-1.0.5 app/models/tb_checkout/cart.rb
tb_checkout-1.0.4 app/models/tb_checkout/cart.rb
tb_checkout-1.0.3 app/models/tb_checkout/cart.rb