Database Reference
In-Depth Information
{"_id" => BSON::ObjectId('4cdf3668238d3b6e32000001'),
"sku"=>"shovel", "state"=>1, "ts"=>"Sun Nov 14 01:07:52 UTC 2010"}
{"_id"=>BSON::ObjectId('4cdf3668238d3b6e32000004'),
"sku"=>"shovel", "state"=>1, "ts"=>"Sun Nov 14 01:07:52 UTC 2010"}
{"_id"=>BSON::ObjectId('4cdf3668238d3b6e32000007'),
"sku"=>"shovel", "state"=>1, "ts"=>"Sun Nov 14 01:07:52 UTC 2010"}
{"_id"=>BSON::ObjectId('4cdf3668238d3b6e32000009'),
"sku"=>"clippers", "state"=>1, "ts"=>"Sun Nov 14 01:07:52 UTC 2010"}
If this InventoryFetcher 's API makes any sense, you should have a least a few hunches
about how you'd implement inventory management. Unsurprisingly, the findAnd-
Modify command resides at its core. The full source code for the InventoryFetcher ,
including a test suite, is included with the source code of this topic. We're not going to
look at every line of code, but we'll highlight the three key methods that make it work.
First, when you pass a list of items to be added to your cart, the fetcher attempts to
transition each item from the state of AVAILABLE to IN_CART . If at any point this opera-
tion fails (if any one item can't be added to the cart), then the entire operation is
rolled back. Have a look at the add_to_cart method that you invoked earlier:
def add_to_cart(order_id, *items)
item_selectors = []
items.each do |item|
item[:qty].times do
item_selectors << {:sku => item[:sku]}
end
end
transition_state(order_id, item_selectors, :from => AVAILABLE,
:to => IN_CART)
end
This method doesn't do much. It basically takes the specification for items to add to
the cart and expands the quantities so that one item selector exists for each physical
item that will be added to the cart. For instance, this document, which says that you
want to add two shovels
{:sku => "shovel", :qty => 2}
becomes this:
[{:sku => "shovel"}, {:sku => "shovel"}]
You need a separate query selector for each item you want to add to your cart. Thus,
the method passes the array of item selectors to another method called transition
_state . For example, the code above specifies that the state should be transitioned
from AVAILABLE to IN_CART :
def transition_state(order_id, selectors, opts={})
items_transitioned = []
begin
for selector in selectors do
Search WWH ::




Custom Search