Database Reference
In-Depth Information
Here's a method that inserts three shovels, three rakes, and three sets of clippers as
available inventory:
3.times do
@inventory.insert({:sku => 'shovel', :state => AVAILABLE})
@inventory.insert({:sku => 'rake', :state => AVAILABLE})
@inventory.insert({:sku => 'clippers', :state => AVAILABLE})
end
We'll handle inventory management with a special inventory fetching class. We'll first
look at how this fetcher works and then we'll peel back the covers to reveal its imple-
mentation.
The inventory fetcher can add arbitrary sets of products to a shopping cart. Here
you create a new order object and a new inventory fetcher. You then ask the fetcher to
add three shovels and one set of clippers to a given order by passing an order ID and
two documents specifying the products and quantities you want to the add_to_cart
method:
@order_id = @orders.insert({:username => 'kbanker', :item_ids => []})
@fetcher = InventoryFetcher.new(:orders => @orders,
:inventory => @inventory)
@fetcher.add_to_cart(@order_id,
{:sku => "shovel", :qty => 3},
{:sku => "clippers", :qty => 1})
order = @orders.find_one({"_id" => @order_id})
puts "\nHere's the order:"
p order
The add_to_cart method will raise an exception if it fails to add every item to a cart.
If it succeeds, the order should look like this:
{"_id" => BSON::ObjectId('4cdf3668238d3b6e3200000a'),
"username"=>"kbanker",
"item_ids" => [BSON::ObjectId('4cdf3668238d3b6e32000001'),
BSON::ObjectId('4cdf3668238d3b6e32000004'),
BSON::ObjectId('4cdf3668238d3b6e32000007'),
BSON::ObjectId('4cdf3668238d3b6e32000009')],
}
The _id of each physical inventory item will be stored in the order document. You can
query for each of these items like so:
puts "\nHere's each item:"
order['item_ids'].each do |item_id|
item = @inventory.find_one({"_id" => item_id})
p item
end
Looking at each of these items individually, you can see that each has a state of 1 , cor-
responding to the IN_CART state. You should also notice that each item records the
time of the last state change with a timestamp. You can later use this timestamp to
expire items that have been in a cart for too long. For instance, you might give users
15 minutes to check out from the time they add products to their cart:
Search WWH ::




Custom Search