Skip to content

Instantly share code, notes, and snippets.

@bobbywilson0
Created January 11, 2010 04:49
Show Gist options
  • Save bobbywilson0/274002 to your computer and use it in GitHub Desktop.
Save bobbywilson0/274002 to your computer and use it in GitHub Desktop.
class Cart
include MongoMapper::Document
many :cart_items
timestamps!
def add_new_item_or_increase_quantity(product_id, quantity)
if self.has_product?(product_id)
self.increment_cart_item_quantity(product_id, quantity)
else
self.add_new_cart_item(product_id, quantity)
end
end
def add_new_cart_item(product_id, quantity)
cart_item = CartItem.new(:product_id => product_id, :quantity => quantity)
self.cart_items << cart_item
end
def increment_cart_item_quantity(product_id, quantity)
cart_item = find_existing_cart_item(product_id)
cart_item.quantity += quantity.to_i
cart_item.save
end
def has_product?(product_id)
if find_existing_cart_item(product_id)
true
else
false
end
end
def find_existing_cart_item(product_id)
self.cart_items.select { |ci| ci.product_id == product_id.to_i }.first
end
end
class CartItem
include MongoMapper::Document
belongs_to :cart
one :product
key :quantity
key :cart_id, ObjectId
end
class Product
include MongoMapper::EmbeddedDocument
key :name, String
key :description, String
key :cart_item_id, ObjectId
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment