Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

198 | Chapter 7: REST, Resources, and Web Services


However, iteliminates the possibility of high availability (sessions cannot be shared
between two servers unless they communicate), and a server that is restarted typi-
cally loses its sessions (unless storing them in persistent storage, which negates many
advantages of sticky sessions). Neither of these options is terribly RESTful, and so we
promote statelessness as far as is practical.


Resourceful session state: An example


So what is the RESTful alternative to holding session state on the server? As with
nearly any problem REST developers face, the solution is tomodel it as a resource.
With the exception of authentication information (discussed later in the chapter),
nearly anything that would be stored in a session could also be factored into a
resource.


Consider the example of a shopping cart. A typical, simple, non-RESTful Rails
implementation would look something like this:


app/models/cart.rb


A simple Hash that defaults to zero.


Used to map product IDs to quantities to represent a shopping cart.


class Cart < Hash
def initialize
super(0)
end
end


app/controllers/carts_controller.rb
class CartsController < ApplicationController
before_filter :set_cart


def add_product
product_id = params[:id]
quantity = params[:quantity] || 1

# Increment cart quantity by provided quantity
session[:cart][product_id.to_i] += quantity.to_i
end

def update_quantity
product_id = params[:id]
quantity = params[:quantity]

# Set cart quantity to provided quantity
session[:cart][product_id.to_i] = quantity.to_i
end

def remove_product
product_id = params[:id]
Free download pdf