Home arrow Ruby-on-Rails arrow Page 4 - Shopping Cart Implementation

Shopping Cart Implementation

Continuing our series on setting up an online bookstore with Ruby-on-Rails, this two-part tutorial explains how to implement the shopping cart. It is excerpted from chapter five of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).

Author Info:
By: Apress Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 13
May 28, 2010
  1. · Shopping Cart Implementation
  2. · Setting Up the Shopping Cart
  3. · Creating the Models
  4. · Modifying the Controller

print this article

Shopping Cart Implementation - Modifying the Controller
(Page 4 of 4 )

Now that we have our models in place, we need to do something to keep a shopping cart at hand while Jill is browsing the store. The easiest way to do that is to use the filter functionality for Rails controllersóin this case, the before_filtermacro. Add the following in the beginning ofCartController (app/controllers/cart_controller.rb) andCatalogController(app/controllers/catalog_controller.rb):  

before_filter :initialize_cart

The filter makes the controller call theinitialize_cartmethod before running an action. We could implement theinitialize_cartmethod in bothCartController andCatalogController, but since we donít want to repeat ourselves, we put the definition to theApplicationController(inapp/controllers/application.rb), which is by default the parent class of all our controllers.

class ApplicationController < ActionController::Base

  def initialize_cart
if session[:cart_id]
@cart = Cart.find(session[:cart_id])
@cart = Cart.create
session[:cart_id] = @cart.id


Filters are a powerful way to control your application logic in your controllers. You can extract common
code from actual actions to filters, and then make those filters run for every appropriate action. The
initialize_cart filter we use for the shopping cart is a good example of filter usage. We want a shopping cart object at hand for every action in CartController and CatalogController, so we extract the cart initialization code in a before_filter.

ActionController offers three types of filters:

  • before_filter: Appends a method call to the before_filter chain of the controller. The chain is
    executed before any affected action is run, and if any of the filters returns false, the chain is aborted and the actual action is not run. Therefore, itís a good way to enforce user authentication, for example, as you will see in Chapter 8.
  • after_filter: Similar to before_filter, except that the after_filter chain is executed after the actual action is run. Therefore, itís not possible to abort the action from an after_filter.
  • around_filter: A combination of the two other types of filters. Using this filter, you can maintain state through the action execution. So, for example, you can use an around_filter to measure the time spent for an action.

Both before_filter and after_filter macros can take the actual filter code parameter in three forms: a symbol, a proc object, or a filter class.

If the first parameter for a filter macro call is a symbol, a method with the same name as the symbol is
executed as the filter:

class CartController < ApplicationController
  before_filter :initialize_cart, :only => [:index, :show]

  def initialize_cart
    # do the magic

For a quick-and-dirty filter, you can use a proc object as filter parameter. The current controller is automatically
passed as a block parameter to the proc.

class AdminController < ApplicationController
  before_filter {|controller| false unless controller.current_user }, ➥
:except => :login

If you want to reuse your filter code in many different places, it might be worth separating the code in its own class:

class LoggingFilter
  def self.filter(controller)
    controller.logger.info "#{controller.request.request_uri} called"

class AdminController < ApplicationController
  after_filter LoggingFilter

When using anaround_filter, you need to use the class form for the filter. In that case, you define methodsbeforeandafterin the filter class, which are then executed before and after the actual action code. Note that you can also use the:onlyand:exceptparameters to restrict the filter calls to only some specific action in a controller.

For more information about ActionController filters, seehttp://api.rubyonrails.org/classes/ ActionController/Filters/ClassMethods.html.

In theinitialize_cartmethod, we check whether there is an item called:cart_idin thesessionhash and if there is, load a cart with thatid, also fetching all of the cartís items with the same query. If nocart_idis stored in the session, we create a new cart and store theidof the new cart to thesessionhash. This way, we can be sure that a single session-wideCartobject is at hand everywhere in bothCatalogControllerandCartController. Once we now know that there is always aCart object@cartpresent, we can also show it in the actions of theCatalogController we created in the previous chapter.

Please check back next week for the conclusion to this article.

DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials