1 #---
2 # Excerpted from "Agile Web Development with Rails, 3rd Ed.",
3 # published by The Pragmatic Bookshelf.
4 # Copyrights apply to this code. It may not be used to create training material,
5 # courses, books, articles, and the like. Contact us if you are in doubt.
6 # We make no guarantees that this code is fit for any purpose.
7 # Visit http://www.pragmaticprogrammer.com/titles/rails3 for more book information.
8 #---
9
10 class StoreController < ApplicationController
11
12
13 before_filter :find_cart, :except => :empty_cart
14
15
16 def index
17 @products = Product.find_products_for_sale
18 end
19
20
21
22
23
24 def add_to_cart
25 product = Product.find(params[:id])
26 @current_item = @cart.add_product(product)
27 respond_to do |format|
28 format.js if request.xhr?
29 format.html {redirect_to_index}
30 end
31 rescue ActiveRecord::RecordNotFound
32 logger.error("Attempt to access invalid product #{params[:id]}")
33 redirect_to_index("Invalid product")
34 end
35
36
37
38
39
40 def checkout
41 if @cart.items.empty?
42 redirect_to_index("Your cart is empty")
43 else
44 @order = Order.new
45 end
46 end
47
48
49
50 def save_order
51 @order = Order.new(params[:order])
52 @order.add_line_items_from_cart(@cart)
53 if @order.save
54 session[:cart] = nil
55 redirect_to_index(I18n.t('flash.thanks'))
56 else
57 render :action => 'checkout'
58 end
59 end
60
61
62 def empty_cart
63 session[:cart] = nil
64 redirect_to_index
65 end
66
67
68 private
69
70
71 def redirect_to_index(msg = nil)
72 flash[:notice] = msg if msg
73 redirect_to :action => 'index'
74 end
75
76
77
78
79 def find_cart
80 @cart = (session[:cart] ||= Cart.new)
81 end
82
83
84
85
86 #...
87 protected
88
89 def authorize
90 end
91 end
92