在處理把商品放入購物車的時候,我們可以看到 Agile Web Development with Rails 4 裡面的範例是把創造一個購物車拉出去放在 moudle 裡面,然後當需要使用的 controller 要用的時候,會include 包進來,而不會寫死在controller裡面,我猜應該是為了保留彈性與延展性,希望書後面會再提到這個優點是什麼。
跟intermediate 課程的做法不太一樣
書裡面
module 的程式碼如下
current_cart.rb
1234567891011121314151617181920
#---# Excerpted from "Agile Web Development with Rails",# published by The Pragmatic Bookshelf.# Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt.# We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.#---moduleCurrentCartextendActiveSupport::Concernprivatedefset_cart@cart=Cart.find(session[:cart_id])rescueActiveRecord::RecordNotFound@cart=Cart.createsession[:cart_id]=@cart.idendend
classLineItemsController<ApplicationControllerincludeCurrentCartbefore_action:set_cart,only:[:create]defcreateproduct=Product.find(params[:product_id])@line_item=@cart.line_items.build(product:product)respond_todo|format|if@line_item.saveformat.html{redirect_to@line_item.cart,notice:'Line item was successfully created.'}format.json{renderaction:'show',status::created,location:@line_item}elseformat.html{renderaction:'new'}format.json{renderjson:@line_item.errors,status::unprocessable_entity}endendend