| Class | StoreController |
| In: |
app/controllers/store_controller.rb
|
| Parent: | ApplicationController |
The StoreController runs the buyer side of our store.
{checkout} Initiate the checkout
Add the given product to the current cart.
# File app/controllers/store_controller.rb, line 17
17: def add_to_cart
18: product = Product.find(params[:id])
19: cart.add_product(product)
20: redirect_to(:action => 'display_cart')
21: rescue
22: logger.error("Attempt to access invalid product #{params[:id]}")
23: redirect_to_index('Invalid product')
24: end
Prompt the user for their contact details and payment method, The checkout procedure is completed by the save_order method.
# File app/controllers/store_controller.rb, line 52
52: def checkout
53: @items = cart.items
54: if @items.empty?
55: redirect_to_index("There's nothing in your cart!")
56: else
57: @order = Order.new
58: @page_title = "Checkout"
59: end
60: end
Display the contents of the cart. If the cart is empty, display a notice and return to the catalog instead.
# File app/controllers/store_controller.rb, line 29
29: def display_cart
30: @items = cart.items
31: if @items.empty?
32: redirect_to_index("Your cart is currently empty")
33: else
34: @page_title = "Your Pragmatic Cart"
35: end
36:
37: if params[:context] == :checkout
38: render_without_layout
39: else
40: render
41: end
42: end
Remove all items from the cart
# File app/controllers/store_controller.rb, line 45
45: def empty_cart
46: cart.empty!
47: redirect_to_index('Your cart is now empty')
48: end
Display the catalog, a list of all saleable products.
# File app/controllers/store_controller.rb, line 12
12: def index
13: @products = Product.salable_items
14: end
Called from checkout view, we convert a cart into an order and save it in the database.
# File app/controllers/store_controller.rb, line 64
64: def save_order
65: @order = Order.new(params[:order])
66: @order.line_items << cart.items
67: if @order.save
68: cart.empty!
69: redirect_to_index('Thank you for your order.')
70: else
71: render_action('checkout')
72: end
73: end
Return a cart object. If we already have one cached in an instance variable, use it. Otherwise, if there’s one in the session, use it. If all else fails, create a new one and add it to the session.
# File app/controllers/store_controller.rb, line 81
81: def cart #:doc:
82: @cart ||= session[:cart]
83: unless @cart
84: @cart = Cart.new
85: session[:cart] = @cart
86: end
87: @cart
88: end