Created
January 11, 2010 04:49
-
-
Save bobbywilson0/274002 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CartItem | |
include MongoMapper::Document | |
belongs_to :cart | |
one :product | |
key :quantity | |
key :cart_id, ObjectId | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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