The Depot Application
Table of Contents
Development Log
rails -v
Rails 2.2.2
ruby -v
ruby 1.8.7 (2008-06-20 patchlevel 22) [i686-darwin9]
gem -v
1.3.1
4 Instant Gratification
erb -r rubygems -r active_support -T - < /Users/rubys/git/awdwr/data/code/erb/ex1.html.erb |
sed 's/<!--.*-->//'
<ul>
<li>Addition: 3 </li>
<li>Concatenation: cowboy </li>
<li>Time in one hour: Fri May 15 14:38:35 -0400 2009 </li>
</ul>
erb -r rubygems -r active_support -T - < /Users/rubys/git/awdwr/data/code/erb/ex2.html.erb |
sed 's/<!--.*-->//'
Ho!<br />
Ho!<br />
Ho!<br />
Merry Christmas!
erb -r rubygems -r active_support -T - < /Users/rubys/git/awdwr/data/code/erb/ex2a.html.erb |
sed 's/<!--.*-->//'
Ho!<br />
Ho!<br />
Ho!<br />
Merry Christmas!
sed 's/-%>\n/%>/' < /Users/rubys/git/awdwr/data/code/erb/ex2b.html.erb |
erb -r rubygems -r active_support -T - |
sed 's/<!--.*-->//'
Ho!<br />
Ho!<br />
Ho!<br />
Merry Christmas!
6.1 Iteration A1: Getting Something Running
rails depot
create
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments
create config/initializers
create config/locales
create db
create doc
create lib
create lib/tasks
create log
create public/images
create public/javascripts
create public/stylesheets
create script/performance
create script/process
create test/fixtures
create test/functional
create test/integration
create test/performance
create test/unit
create vendor
create vendor/plugins
create tmp/sessions
create tmp/sockets
create tmp/cache
create tmp/pids
create Rakefile
create README
create app/controllers/application.rb
create app/helpers/application_helper.rb
create test/test_helper.rb
create test/performance/browsing_test.rb
create config/database.yml
create config/routes.rb
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/new_rails_defaults.rb
create config/locales/en.yml
create config/boot.rb
create config/environment.rb
create config/environments/production.rb
create config/environments/development.rb
create config/environments/test.rb
create script/about
create script/console
create script/dbconsole
create script/destroy
create script/generate
create script/performance/benchmarker
create script/performance/profiler
create script/performance/request
create script/process/reaper
create script/process/spawner
create script/process/inspector
create script/runner
create script/server
create script/plugin
create public/dispatch.rb
create public/dispatch.cgi
create public/dispatch.fcgi
create public/404.html
create public/422.html
create public/500.html
create public/index.html
create public/favicon.ico
create public/robots.txt
create public/images/rails.png
create public/javascripts/prototype.js
create public/javascripts/effects.js
create public/javascripts/dragdrop.js
create public/javascripts/controls.js
create public/javascripts/application.js
create doc/README_FOR_APP
create log/server.log
create log/production.log
create log/development.log
create log/test.log
edit config/environments/development.rb
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
config.logger = Logger.new(config.log_path, 2, 10.kilobytes)
6.2 Creating the Products Model and Maintenance Application
ls -p
README
Rakefile
app/
config/
db/
doc/
lib/
log/
public/
script/
test/
tmp/
vendor/
ruby script/generate scaffold product title:string description:text image_url:string
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/products
exists app/views/layouts/
exists test/functional/
exists test/unit/
exists public/stylesheets/
create app/views/products/index.html.erb
create app/views/products/show.html.erb
create app/views/products/new.html.erb
create app/views/products/edit.html.erb
create app/views/layouts/products.html.erb
create public/stylesheets/scaffold.css
create app/controllers/products_controller.rb
create test/functional/products_controller_test.rb
create app/helpers/products_helper.rb
route map.resources :products
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/product.rb
create test/unit/product_test.rb
create test/fixtures/products.yml
create db/migrate
create db/migrate/20090515173845_create_products.rb
rake db:migrate
mv 20090515173845_create_products.rb 20080601000001_create_products.rb
(in /Users/rubys/git/awdwr/work/depot)
== CreateProducts: migrating =================================================
-- create_table(:products)
-> 0.0041s
== CreateProducts: migrated (0.0043s) ========================================
sqlite3> select version from schema_migrations
version = 20080601000001
restart
edit app/views/products/new.html.erb
<h1>New product</h1>
<% form_for(@product) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.label :description %><br />
<%= f.text_area :description, :rows => 6 %>
</p>
<p>
<%= f.label :image_url %><br />
<%= f.text_field :image_url %>
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
<%= link_to 'Back', products_path %>
get /products
Listing products
Title
Description
Image url
New product
get /products/new
post /products
product[image_url] => /images/svn.jpg
product[description] => <p>
This book is a recipe-based approach to
using Subversion that will get you up
and running quickly---and correctly. All
projects need version control: it's a
foundational piece of any project's
infrastructure. Yet half of all project
teams in the U.S. dont use any version
control at all. Many others dont use it
well, and end up experiencing
time-consuming problems.
</p>
product[title] => Pragmatic Version Control
You are being
redirected .
get http://127.0.0.1:3000/products/1
Title:
Pragmatic Version Control
Description:
<p>
This book is a recipe-based approach to
using Subversion that will get you up
and running quickly---and correctly. All
projects need version control: it's a
foundational piece of any project's
infrastructure. Yet half of all project
teams in the U.S. dont use any version
control at all. Many others dont use it
well, and end up experiencing
time-consuming problems.
</p>
Image url:
/images/svn.jpg
Edit |
Back
get /products
Listing products
Title
Description
Image url
Pragmatic Version Control
<p>
This book is a recipe-based approach to
using Subversion that will get you up
and running quickly---and correctly. All
projects need version control: it's a
foundational piece of any project's
infrastructure. Yet half of all project
teams in the U.S. dont use any version
control at all. Many others dont use it
well, and end up experiencing
time-consuming problems.
</p>
/images/svn.jpg
Show
Edit
Destroy
New product
sqlite3 db/development.sqlite3 .schema
CREATE TABLE "products" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "description" text, "image_url" varchar(255), "created_at" datetime, "updated_at" datetime);
CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);
CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version");
rake test
(in /Users/rubys/git/awdwr/work/depot)
/opt/local/bin/ruby -Ilib:test "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/unit/product_test.rb"
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Started
.
Finished in 0.341516 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
/opt/local/bin/ruby -Ilib:test "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/functional/products_controller_test.rb"
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Started
.......
Finished in 0.361773 seconds.
7 tests, 10 assertions, 0 failures, 0 errors
/opt/local/bin/ruby -Ilib:test "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb"
6.3 Iteration A2: Add a Missing Column
ruby script/generate migration add_price_to_product price:decimal
exists db/migrate
create db/migrate/20090515173918_add_price_to_product.rb
cat db/migrate/20090515173918_add_price_to_product.rb
class AddPriceToProduct < ActiveRecord::Migration
def self.up
add_column :products, :price, :decimal
end
def self.down
remove_column :products, :price
end
end
edit db/migrate/20090515173918_add_price_to_product.rb
class AddPriceToProduct < ActiveRecord::Migration
def self.up
add_column :products, :price, :decimal,
:precision => 8, :scale => 2, :default => 0
end
def self.down
remove_column :products, :price
end
end
rake db:migrate
mv 20090515173918_add_price_to_product.rb 20080601000002_add_price_to_product.rb
(in /Users/rubys/git/awdwr/work/depot)
== AddPriceToProduct: migrating ==============================================
-- add_column(:products, :price, :decimal, {:default=>0, :precision=>8, :scale=>2})
-> 0.0186s
== AddPriceToProduct: migrated (0.0188s) =====================================
sqlite3 db/development.sqlite3 .schema
CREATE TABLE "products" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "description" text, "image_url" varchar(255), "created_at" datetime, "updated_at" datetime, "price" decimal(8,2) DEFAULT 0);
CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);
CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version");
edit app/views/products/index.html.erb
<h1>Listing products</h1>
<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Image url</th>
<th>Price</th>
</tr>
<% for product in @products %>
<tr>
<td><%=h product.title %></td>
<td><%=h product.description %></td>
<td><%=h product.image_url %></td>
<td><%=h product.price %></td>
<td><%= link_to 'Show', product %></td>
<td><%= link_to 'Edit', edit_product_path(product) %></td>
<td><%= link_to 'Destroy', product, :confirm => 'Are you sure?',
:method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New product', new_product_path %>
edit app/views/products/new.html.erb
<h1>New product</h1>
<% form_for(@product) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.label :description %><br />
<%= f.text_area :description, :rows => 6 %>
</p>
<p>
<%= f.label :image_url %><br />
<%= f.text_field :image_url %>
</p>
<p>
<%= f.label :price %><br />
<%= f.text_field :price %>
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
<%= link_to 'Back', products_path %>
edit app/views/products/edit.html.erb
<h1>Editing product</h1>
<% form_for(@product) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.label :description %><br />
<%= f.text_area :description %>
</p>
<p>
<%= f.label :image_url %><br />
<%= f.text_field :image_url %>
</p>
<p>
<%= f.label :price %><br />
<%= f.text_field :price %>
</p>
<p>
<%= f.submit "Update" %>
</p>
<% end %>
<%= link_to 'Show', @product %> |
<%= link_to 'Back', products_path %>
edit app/views/products/show.html.erb
<p>
<b>Title:</b>
<%=h @product.title %>
</p>
<p>
<b>Description:</b>
<%=h @product.description %>
</p>
<p>
<b>Image url:</b>
<%=h @product.image_url %>
</p>
<p>
<b>Price:</b>
<%=h @product.price %>
</p>
<%= link_to 'Edit', edit_product_path(@product) %> |
<%= link_to 'Back', products_path %>
get /products
Listing products
Title
Description
Image url
Price
Pragmatic Version Control
<p>
This book is a recipe-based approach to
using Subversion that will get you up
and running quickly---and correctly. All
projects need version control: it's a
foundational piece of any project's
infrastructure. Yet half of all project
teams in the U.S. dont use any version
control at all. Many others dont use it
well, and end up experiencing
time-consuming problems.
</p>
/images/svn.jpg
0.0
Show
Edit
Destroy
New product
get /products/1
Title:
Pragmatic Version Control
Description:
<p>
This book is a recipe-based approach to
using Subversion that will get you up
and running quickly---and correctly. All
projects need version control: it's a
foundational piece of any project's
infrastructure. Yet half of all project
teams in the U.S. dont use any version
control at all. Many others dont use it
well, and end up experiencing
time-consuming problems.
</p>
Image url:
/images/svn.jpg
Price:
0.0
Edit |
Back
get /products/new
rake test
(in /Users/rubys/git/awdwr/work/depot)
/opt/local/bin/ruby -Ilib:test "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/unit/product_test.rb"
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Started
.
Finished in 0.108685 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
/opt/local/bin/ruby -Ilib:test "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/functional/products_controller_test.rb"
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Started
.......
Finished in 0.369828 seconds.
7 tests, 10 assertions, 0 failures, 0 errors
/opt/local/bin/ruby -Ilib:test "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb"
edit app/views/products/show.html.erb
<p>
<b>Title:</b>
<%=h @product.title %>
</p>
<p>
<b>Description:</b>
<%= @product.description %>
</p>
<p>
<b>Image url:</b>
<%=h @product.image_url %>
</p>
<p>
<b>Price:</b>
<%=h @product.price %>
</p>
<%= link_to 'Edit', edit_product_path(@product) %> |
<%= link_to 'Back', products_path %>
get /products/1
Title:
Pragmatic Version Control
Description:
This book is a recipe-based approach to
using Subversion that will get you up
and running quickly---and correctly. All
projects need version control: it's a
foundational piece of any project's
infrastructure. Yet half of all project
teams in the U.S. dont use any version
control at all. Many others dont use it
well, and end up experiencing
time-consuming problems.
Image url:
/images/svn.jpg
Price:
0.0
Edit |
Back
6.4 Iteration A3: Validate!
edit app/models/product.rb
class Product < ActiveRecord::Base
validates_presence_of :title, :description, :image_url
validates_numericality_of :price
validate :price_must_be_at_least_a_cent
validates_uniqueness_of :title
validates_format_of :image_url, :allow_blank => true,
:with => %r{\.(gif|jpg|png)$}i,
:message => 'must be a URL for GIF, JPG ' +
'or PNG image.'
protected
def price_must_be_at_least_a_cent
errors.add(:price, 'should be at least 0.01') if price.nil? ||
price < 0.00
end
end
get /products/new
post /products
New product
3 errors prohibited this product from being saved There were problems with the following fields:
Image url can't be blank Title can't be blank Description can't be blank
Title
Description
Image url
Price
Back
get /products/new
post /products
product[image_url] => /images/utj.jpg
product[price] => wibble
product[description] => A true masterwork. Comparable to Kafka at
his funniest, or Marx during his slapstick
period. Move over, Tolstoy, there's a new
funster in town.
product[title] => Pragmatic Unit Testing
edit app/models/product.rb
class Product < ActiveRecord::Base
validates_presence_of :title, :description, :image_url
validates_numericality_of :price
validate :price_must_be_at_least_a_cent
validates_uniqueness_of :title
validates_format_of :image_url,
:with => %r{\.(gif|jpg|png)$}i,
:message => 'must be a URL for GIF, JPG ' +
'or PNG image.'
protected
def price_must_be_at_least_a_cent
errors.add(:price, 'should be at least 0.01') if price.nil? ||
price < 0.01
end
end
edit app/views/layouts/products.html.erb
6.5 Iteration A4: Making Prettier Listings
edit db/migrate/003_add_test_data.rb
class AddTestData < ActiveRecord::Migration
def self.up
Product.delete_all
Product.create(:title => 'Pragmatic Version Control',
:description =>
%{<p>
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
</p>},
:image_url => '/images/svn.jpg',
:price => 28.50)
# . . .
end
def self.down
Product.delete_all
end
end
rake db:migrate
mv 003_add_test_data.rb 20080601000003_add_test_data.rb
(in /Users/rubys/git/awdwr/work/depot)
== AddTestData: migrating ====================================================
== AddTestData: migrated (0.0615s) ===========================================
edit app/views/layouts/products.html.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Products: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold', 'depot' %>
</head>
edit app/views/products/index.html.erb
<div id="product-list">
<h1>Listing products</h1>
<table>
<% for product in @products %>
<tr class="<%= cycle('list-line-odd', 'list-line-even') %>">
<td>
<%= image_tag product.image_url, :class => 'list-image' %>
</td>
<td class="list-description">
<dl>
<dt><%=h product.title %></dt>
<dd><%=h truncate(product.description.gsub(/<.*?>/,''),
:length => 80) %></dd>
</dl>
</td>
<td class="list-actions">
<%= link_to 'Show', product %><br/>
<%= link_to 'Edit', edit_product_path(product) %><br/>
<%= link_to 'Destroy', product,
:confirm => 'Are you sure?',
:method => :delete %>
</td>
</tr>
<% end %>
</table>
</div>
<br />
<%= link_to 'New product', new_product_path %>
cp -v /Users/rubys/git/awdwr/data/images/* public/images/
/Users/rubys/git/awdwr/data/images/auto.jpg -> public/images/auto.jpg
/Users/rubys/git/awdwr/data/images/logo.png -> public/images/logo.png
/Users/rubys/git/awdwr/data/images/rails.png -> public/images/rails.png
/Users/rubys/git/awdwr/data/images/svn.jpg -> public/images/svn.jpg
/Users/rubys/git/awdwr/data/images/utc.jpg -> public/images/utc.jpg
cp -v /Users/rubys/git/awdwr/data/depot.css public/stylesheets
/Users/rubys/git/awdwr/data/depot.css -> public/stylesheets/depot.css
get /products
7.1 Iteration B1: Create the Catalog Listing
ruby script/generate controller store index
exists app/controllers/
exists app/helpers/
create app/views/store
exists test/functional/
create app/controllers/store_controller.rb
create test/functional/store_controller_test.rb
create app/helpers/store_helper.rb
create app/views/store/index.html.erb
restart
get /store
Store#index
Find me in app/views/store/index.html.erb
edit app/controllers/store_controller.rb
class StoreController < ApplicationController
def index
@products = Product.find_products_for_sale
end
end
edit app/models/product.rb
class Product < ActiveRecord::Base
def self.find_products_for_sale
find(:all, :order => "title")
end
# validation stuff...
validates_presence_of :title, :description, :image_url
validates_numericality_of :price
validate :price_must_be_at_least_a_cent
validates_uniqueness_of :title
validates_format_of :image_url,
:with => %r{\.(gif|jpg|png)$}i,
:message => 'must be a URL for GIF, JPG ' +
'or PNG image.'
protected
def price_must_be_at_least_a_cent
errors.add(:price, 'should be at least 0.01') if price.nil? ||
price < 0.01
end
end
edit app/views/store/index.html.erb
<h1>Your Pragmatic Catalog</h1>
<% for product in @products -%>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%=h product.title %></h3>
<%= product.description %>
<div class="price-line">
<span class="price"><%= product.price %></span>
</div>
</div>
<% end %>
get /store
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
29.95
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
27.75
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
28.5
7.2 Iteration B2: Add a Page Layout
edit app/views/layouts/store.html.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Pragprog Books Online Store</title>
<%= stylesheet_link_tag "depot", :media => "all" %><!-- <label id="code.slt"/> -->
</head>
<body id="store">
<div id="banner">
<%= image_tag("logo.png") %>
<%= @page_title || "Pragmatic Bookshelf" %><!-- <label id="code.depot.e.title"/> -->
</div>
<div id="columns">
<div id="side">
<a href="http://www....">Home</a><br />
<a href="http://www..../faq">Questions</a><br />
<a href="http://www..../news">News</a><br />
<a href="http://www..../contact">Contact</a><br />
</div>
<div id="main">
<%= yield :layout %><!-- <label id="code.depot.e.include"/> -->
</div>
</div>
</body>
</html>
edit public/stylesheets/depot.css
/* Styles for main page */
#banner {
background: #9c9;
padding-top: 10px;
padding-bottom: 10px;
border-bottom: 2px solid;
font: small-caps 40px/40px "Times New Roman", serif;
color: #282;
text-align: center;
}
#banner img {
float: left;
}
#columns {
background: #141;
}
#main {
margin-left: 13em;
padding-top: 4ex;
padding-left: 2em;
background: white;
}
#side {
float: left;
padding-top: 1em;
padding-left: 1em;
padding-bottom: 1em;
width: 12em;
background: #141;
}
#side a {
color: #bfb;
font-size: small;
}
get /store
Pragmatic Bookshelf
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
29.95
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
27.75
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
28.5
7.3 Iteration B3: Use a Helper to Format the Price
edit app/views/store/index.html.erb
<h1>Your Pragmatic Catalog</h1>
<% for product in @products -%>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%=h product.title %></h3>
<%= product.description %>
<div class="price-line">
<span class="price"><%= number_to_currency(product.price) %></span>
</div>
</div>
<% end %>
get /store
Pragmatic Bookshelf
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
$29.95
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
$27.75
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
$28.50
7.4 Iteration B4: Linking to the Cart
edit app/views/store/index.html.erb
<%= button_to "Add to Cart" %>
edit public/stylesheets/depot.css
#store .entry form, #store .entry form div {
display: inline;
}
get /store
Pragmatic Bookshelf
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
8.1 Sessions
rake db:sessions:create
(in /Users/rubys/git/awdwr/work/depot)
exists db/migrate
create db/migrate/20090515174007_create_sessions.rb
rake db:migrate
mv 20090515174007_create_sessions.rb 20080601000004_create_sessions.rb
(in /Users/rubys/git/awdwr/work/depot)
== CreateSessions: migrating =================================================
-- create_table(:sessions)
-> 0.0164s
-- add_index(:sessions, :session_id)
-> 0.0026s
-- add_index(:sessions, :updated_at)
-> 0.0026s
== CreateSessions: migrated (0.0221s) ========================================
sqlite3 db/development.sqlite3 .schema
CREATE TABLE "products" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "description" text, "image_url" varchar(255), "created_at" datetime, "updated_at" datetime, "price" decimal(8,2) DEFAULT 0);
CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);
CREATE TABLE "sessions" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "session_id" varchar(255) NOT NULL, "data" text, "created_at" datetime, "updated_at" datetime);
CREATE INDEX "index_sessions_on_session_id" ON "sessions" ("session_id");
CREATE INDEX "index_sessions_on_updated_at" ON "sessions" ("updated_at");
CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version");
edit config/environment.rb
# Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# See Rails::Configuration for more options.
# Skip frameworks you're not going to use. To use Rails without a database
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Specify gems that this application depends on.
# They can then be installed with "rake gems:install" on new installations.
# You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3)
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Make Time.zone default to the specified zone, and make Active Record store time values
# in the database in UTC, and return them converted to the specified local zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time.
config.time_zone = 'UTC'
# The internationalization framework can be changed to have another default locale (standard is :en) or more load paths.
# All files from config/locales/*.rb,yml are added automatically.
# config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_depot_session',
:secret => 'd5ee2116747855920b0c30c7594ce6c9a8456f342ce442f99f967301c4b9f5ca50dec9a18031f7b8acbdf5496187e88384f2db56892c042ae254afde5a4d9c26'
}
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
config.action_controller.session_store = :active_record_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# Please note that observers generated using script/generate observer need to have an _observer suffix
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
end
restart
edit app/controllers/application.rb
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery :secret => '156f9e3d5ab2773114a2ec10be357e0a'
# See ActionController::Base for details
# Uncomment this to filter the contents of submitted sensitive data parameters
# from your application log (in this case, all fields with names like "password").
# filter_parameter_logging :password
end
edit app/controllers/store_controller.rb
private
def find_cart
session[:cart] ||= Cart.new
end
8.2 Iteration C1: Creating a Cart
edit app/models/cart.rb
class Cart
attr_reader :items # <wtf linkend="wtf.attr.accessor">attr_reader</wtf>
def initialize
@items = []
end
def add_product(product)
@items << product
end
end
edit app/views/store/index.html.erb
<%= button_to "Add to Cart", :action => 'add_to_cart', :id => product %>
edit app/controllers/store_controller.rb
def add_to_cart
product = Product.find(params[:id]) # <label id="code.depot.f.find"/>
@cart = find_cart # <label id="code.depot.f.find2"/>
@cart.add_product(product) # <label id="code.depot.f.add"/>
end
get /store/add_to_cart/2
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Action Controller: Exception caught</title>
<style>
body { background-color: #fff; color: #333; }
body, p, ol, ul, td {
font-family: verdana, arial, helvetica, sans-serif;
font-size: 13px;
line-height: 18px;
}
pre {
background-color: #eee;
padding: 10px;
font-size: 11px;
}
a { color: #000; }
a:visited { color: #666; }
a:hover { color: #fff; background-color:#000; }
</style>
</head>
<body>
<h1>Template is missing</h1>
<p>Missing template store/add_to_cart.erb in view path /Users/rubys/git/awdwr/work/depot/app/views:</p>
</body>
</html>
edit app/views/store/add_to_cart.html.erb
<h2>Your Pragmatic Cart</h2>
<ul>
<% for item in @cart.items %>
<li><%=h item.title %></li>
<% end %>
</ul>
get /store/add_to_cart/2
Pragmatic Bookshelf
Your Pragmatic Cart
Pragmatic Project Automation
Pragmatic Project Automation
get /store/add_to_cart/3
Pragmatic Bookshelf
Your Pragmatic Cart
Pragmatic Project Automation
Pragmatic Project Automation
Pragmatic Version Control
8.3 Iteration C2: Creating a Smarter Cart
edit app/models/cart_item.rb
class CartItem
attr_reader :product, :quantity
def initialize(product)
@product = product
@quantity = 1
end
def increment_quantity
@quantity += 1
end
def title
@product.title
end
def price
@product.price * @quantity
end
end
edit app/models/cart.rb
def add_product(product)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity
else
@items << CartItem.new(product)
end
end
edit app/views/store/add_to_cart.html.erb
<h2>Your Pragmatic Cart</h2>
<ul>
<% for item in @cart.items %>
<li><%= item.quantity %> × <%=h item.title %></li>
<% end %>
</ul>
get /store/add_to_cart/2
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Action Controller: Exception caught</title>
<style>
body { background-color: #fff; color: #333; }
body, p, ol, ul, td {
font-family: verdana, arial, helvetica, sans-serif;
font-size: 13px;
line-height: 18px;
}
pre {
background-color: #eee;
padding: 10px;
font-size: 11px;
}
a { color: #000; }
a:visited { color: #666; }
a:hover { color: #fff; background-color:#000; }
</style>
</head>
<body>
<h1>
NoMethodError
in StoreController#add_to_cart
</h1>
<pre>undefined method `product' for #<Product:0x272ddbc></pre>
<p><code>RAILS_ROOT: /Users/rubys/git/awdwr/work/depot</code></p>
<div id="traces">
<a href="#" onclick="document.getElementById('Framework-Trace').style.display='none';document.getElementById('Full-Trace').style.display='none';document.getElementById('Application-Trace').style.display='block';; return false;">Application Trace</a> |
<a href="#" onclick="document.getElementById('Application-Trace').style.display='none';document.getElementById('Full-Trace').style.display='none';document.getElementById('Framework-Trace').style.display='block';; return false;">Framework Trace</a> |
<a href="#" onclick="document.getElementById('Application-Trace').style.display='none';document.getElementById('Framework-Trace').style.display='none';document.getElementById('Full-Trace').style.display='block';; return false;">Full Trace</a>
<div id="Application-Trace" style="display: block;">
<pre><code>/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/attribute_methods.rb:260:in `method_missing'
app/models/cart.rb:10:in `add_product'
app/models/cart.rb:10:in `each'
app/models/cart.rb:10:in `find'
app/models/cart.rb:10:in `add_product'
app/controllers/store_controller.rb:11:in `add_to_cart'
makedepot.rb:2300:in `restart_server'
makedepot.rb:346
makedepot.rb:2374:in `call'
makedepot.rb:2374
makedepot.rb:2371:in `each'
makedepot.rb:2371
makedepot.rb:2334
makedepot.rb:2307</code></pre>
</div>
<div id="Framework-Trace" style="display: none;">
<pre><code>/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/attribute_methods.rb:260:in `method_missing'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1907:in `find'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1253:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1253:in `perform_action_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:617:in `call_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:610:in `perform_action_without_benchmark'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/1.8/benchmark.rb:293:in `measure'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/rescue.rb:136:in `perform_action_without_caching'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:13:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/query_cache.rb:34:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/query_cache.rb:8:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:12:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `process_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:606:in `process_without_session_management_support'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/session_management.rb:134:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:392:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:183:in `handle_request'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:110:in `dispatch_unlocked'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:123:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:132:in `dispatch_cgi'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:39:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:76:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:159:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:282:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:128:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/command.rb:212:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load_without_new_constant_marking'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/servers/mongrel.rb:64
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/server.rb:49
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'</code></pre>
</div>
<div id="Full-Trace" style="display: none;">
<pre><code>/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/attribute_methods.rb:260:in `method_missing'
app/models/cart.rb:10:in `add_product'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1907:in `find'
app/models/cart.rb:10:in `each'
app/models/cart.rb:10:in `find'
app/models/cart.rb:10:in `add_product'
app/controllers/store_controller.rb:11:in `add_to_cart'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1253:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1253:in `perform_action_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:617:in `call_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:610:in `perform_action_without_benchmark'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/1.8/benchmark.rb:293:in `measure'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/rescue.rb:136:in `perform_action_without_caching'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:13:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/query_cache.rb:34:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/query_cache.rb:8:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:12:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `process_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:606:in `process_without_session_management_support'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/session_management.rb:134:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:392:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:183:in `handle_request'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:110:in `dispatch_unlocked'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:123:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:132:in `dispatch_cgi'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:39:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:76:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:159:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:282:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:128:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/command.rb:212:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load_without_new_constant_marking'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/servers/mongrel.rb:64
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/server.rb:49
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
makedepot.rb:2300:in `restart_server'
makedepot.rb:346
makedepot.rb:2374:in `call'
makedepot.rb:2374
makedepot.rb:2371:in `each'
makedepot.rb:2371
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
makedepot.rb:2334
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
makedepot.rb:2307</code></pre>
</div>
</div>
<h2 style="margin-top: 30px">Request</h2>
<p><b>Parameters</b>: <pre>{"id"=>"2"}</pre></p>
<p><a href="#" onclick="document.getElementById('session_dump').style.display='block'; return false;">Show session dump</a></p>
<div id="session_dump" style="display:none"><pre class='debug_dump'>---
flash: !map:ActionController::Flash::FlashHash {}
:cart: !ruby/object:Cart
items:
- !ruby/object:Product
attributes:
price: "29.95"
created_at: 2009-05-15 17:39:48
title: Pragmatic Project Automation
image_url: /images/auto.jpg
updated_at: 2009-05-15 17:39:48
id: "2"
description: |-
<p>
<em>Pragmatic Project Automation</em> shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
</p>
<p>
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
</p>
attributes_cache: {}
- !ruby/object:Product
attributes:
price: "29.95"
created_at: 2009-05-15 17:39:48
image_url: /images/auto.jpg
title: Pragmatic Project Automation
updated_at: 2009-05-15 17:39:48
id: "2"
description: |-
<p>
<em>Pragmatic Project Automation</em> shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
</p>
<p>
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
</p>
attributes_cache: {}
- !ruby/object:Product
attributes:
price: "28.5"
created_at: 2009-05-15 17:39:48
title: Pragmatic Version Control
image_url: /images/svn.jpg
updated_at: 2009-05-15 17:39:48
id: "3"
description: |-
<p>
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
</p>
attributes_cache: {}
</pre></div>
<h2 style="margin-top: 30px">Response</h2>
<p><b>Headers</b>: <pre>{"Content-Type"=>"",
"cookie"=>[],
"Cache-Control"=>"no-cache"}</pre></p>
</body>
</html>
rake db:sessions:clear
(in /Users/rubys/git/awdwr/work/depot)
get /store/add_to_cart/2
Pragmatic Bookshelf
Your Pragmatic Cart
1 × Pragmatic Project Automation
get /store/add_to_cart/2
Pragmatic Bookshelf
Your Pragmatic Cart
2 × Pragmatic Project Automation
get /store/add_to_cart/3
Pragmatic Bookshelf
Your Pragmatic Cart
2 × Pragmatic Project Automation
1 × Pragmatic Version Control
get /store/add_to_cart/wibble
ActiveRecord::RecordNotFound
in StoreController#add_to_cart
Couldn't find Product with ID=wibble
RAILS_ROOT: /Users/rubys/git/awdwr/work/depot
Application Trace |
Framework Trace |
Full Trace
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1528:in `find_one'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1511:in `find_from_ids'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:590:in `find'
app/controllers/store_controller.rb:9:in `add_to_cart'
makedepot.rb:2300:in `restart_server'
makedepot.rb:346
makedepot.rb:2374:in `call'
makedepot.rb:2374
makedepot.rb:2371:in `each'
makedepot.rb:2371
makedepot.rb:2334
makedepot.rb:2307
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1528:in `find_one'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1511:in `find_from_ids'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:590:in `find'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1253:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1253:in `perform_action_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:617:in `call_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:610:in `perform_action_without_benchmark'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/1.8/benchmark.rb:293:in `measure'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/rescue.rb:136:in `perform_action_without_caching'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:13:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/query_cache.rb:34:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/query_cache.rb:8:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:12:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `process_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:606:in `process_without_session_management_support'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/session_management.rb:134:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:392:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:183:in `handle_request'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:110:in `dispatch_unlocked'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:123:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:132:in `dispatch_cgi'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:39:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:76:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:159:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:282:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:128:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/command.rb:212:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load_without_new_constant_marking'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/servers/mongrel.rb:64
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/server.rb:49
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1528:in `find_one'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1511:in `find_from_ids'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:590:in `find'
app/controllers/store_controller.rb:9:in `add_to_cart'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1253:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1253:in `perform_action_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:617:in `call_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:610:in `perform_action_without_benchmark'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/1.8/benchmark.rb:293:in `measure'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/rescue.rb:136:in `perform_action_without_caching'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:13:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/query_cache.rb:34:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/query_cache.rb:8:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:12:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `process_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:606:in `process_without_session_management_support'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/session_management.rb:134:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:392:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:183:in `handle_request'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:110:in `dispatch_unlocked'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:123:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:132:in `dispatch_cgi'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:39:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:76:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:159:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:282:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:128:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/command.rb:212:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load_without_new_constant_marking'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/servers/mongrel.rb:64
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/server.rb:49
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
makedepot.rb:2300:in `restart_server'
makedepot.rb:346
makedepot.rb:2374:in `call'
makedepot.rb:2374
makedepot.rb:2371:in `each'
makedepot.rb:2371
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
makedepot.rb:2334
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
makedepot.rb:2307
Request
Parameters :
{"id"=>"wibble"}
Show session dump
---
flash: !map:ActionController::Flash::FlashHash {}
:cart: !ruby/object:Cart
items:
- !ruby/object:CartItem
product: !ruby/object:Product
attributes:
price: "29.95"
created_at: 2009-05-15 17:39:48
title: Pragmatic Project Automation
image_url: /images/auto.jpg
updated_at: 2009-05-15 17:39:48
id: "2"
description: |-
<p>
<em>Pragmatic Project Automation</em> shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
</p>
<p>
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
</p>
attributes_cache: {}
quantity: 2
- !ruby/object:CartItem
product: !ruby/object:Product
attributes:
price: "28.5"
created_at: 2009-05-15 17:39:48
title: Pragmatic Version Control
image_url: /images/svn.jpg
updated_at: 2009-05-15 17:39:48
id: "3"
description: |-
<p>
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
</p>
attributes_cache: {}
quantity: 1
Response
Headers :
{"Content-Type"=>"",
"cookie"=>[],
"Cache-Control"=>"no-cache"}
8.4 Iteration C3: Handling Errors
edit app/controllers/store_controller.rb
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@cart.add_product(product)
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
flash[:notice] = "Invalid product"
redirect_to :action => 'index'
end
get /store/add_to_cart/wibble
You are being
redirected .
get http://127.0.0.1:3000/store
Pragmatic Bookshelf
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
tail -17 log/development.log
Processing StoreController#add_to_cart (for 127.0.0.1 at 2009-05-15 13:40:28) [GET]
Session ID: 49a9fce127ae939959f9816558addf8b
Parameters: {"id"=>"wibble"}
*[4;36;1mProduct Load (0.3ms)*[0m *[0;1mSELECT * FROM "products" WHERE ("products"."id" = 0) *[0m
Attempt to access invalid product wibble
Redirected to actionindex
Completed in 17ms (DB: 4) | 302 Found [http://127.0.0.1/store/add_to_cart/wibble]
Processing StoreController#index (for 127.0.0.1 at 2009-05-15 13:40:28) [GET]
Session ID: 49a9fce127ae939959f9816558addf8b
*[4;35;1mProduct Load (1.7ms)*[0m *[0mSELECT * FROM "products" ORDER BY title*[0m
Rendering template within layouts/store
Rendering store/index
Completed in 143ms (View: 130, DB: 5) | 200 OK [http://127.0.0.1/store]
edit app/views/layouts/store.html.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Pragprog Books Online Store</title>
<%= stylesheet_link_tag "depot", :media => "all" %>
</head>
<body id="store">
<div id="banner">
<%= image_tag("logo.png") %>
<%= @page_title || "Pragmatic Bookshelf" %>
</div>
<div id="columns">
<div id="side">
<a href="http://www....">Home</a><br />
<a href="http://www..../faq">Questions</a><br />
<a href="http://www..../news">News</a><br />
<a href="http://www..../contact">Contact</a><br />
</div>
<div id="main">
<% if flash[:notice] -%>
<div id="notice"><%= flash[:notice] %></div>
<% end -%>
<%= yield :layout %>
</div>
</div>
</body>
</html>
edit public/stylesheets/depot.css
#notice {
border: 2px solid red;
padding: 1em;
margin-bottom: 2em;
background-color: #f0f0f0;
font: bold smaller sans-serif;
}
get /store/add_to_cart/wibble
You are being
redirected .
get http://127.0.0.1:3000/store
Pragmatic Bookshelf
Invalid product
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
8.5 Iteration C4: Finishing the Cart
edit app/views/store/add_to_cart.html.erb
<h2>Your Pragmatic Cart</h2>
<ul>
<% for item in @cart.items %>
<li><%= item.quantity %> × <%=h item.title %></li>
<% end %>
</ul>
<%= button_to 'Empty cart', :action => 'empty_cart' %>
edit app/controllers/store_controller.rb
def empty_cart
session[:cart] = nil
flash[:notice] = "Your cart is currently empty"
redirect_to :action => 'index'
end
get /store/empty_cart
You are being
redirected .
get http://127.0.0.1:3000/store
Pragmatic Bookshelf
Your cart is currently empty
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
edit app/controllers/store_controller.rb
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@cart.add_product(product)
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
end
def empty_cart
session[:cart] = nil
redirect_to_index("Your cart is currently empty")
end
private
def redirect_to_index(msg)
flash[:notice] = msg
redirect_to :action => 'index'
end
edit app/views/store/add_to_cart.html.erb
<div class="cart-title">Your Cart</div>
<table>
<% for item in @cart.items %>
<tr>
<td><%= item.quantity %>×</td>
<td><%=h item.title %></td>
<td class="item-price"><%= number_to_currency(item.price) %></td>
</tr>
<% end %>
<tr class="total-line">
<td colspan="2">Total</td>
<td class="total-cell"><%= number_to_currency(@cart.total_price) %></td>
</tr>
</table>
<%= button_to "Empty cart", :action => :empty_cart %>
edit public/stylesheets/depot.css
/* Styles for the cart in the main page */
.cart-title {
font: 120% bold;
}
.item-price, .total-line {
text-align: right;
}
.total-line .total-cell {
font-weight: bold;
border-top: 1px solid #595;
}
edit app/models/cart.rb
class Cart
attr_reader :items # <wtf linkend="wtf.attr.accessor">attr_reader</wtf>
def initialize
@items = []
end
def add_product(product)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity
else
@items << CartItem.new(product)
end
end
def total_price
@items.sum { |item| item.price }
end
end
get /store/add_to_cart/2
Pragmatic Bookshelf
get /store/add_to_cart/2
Pragmatic Bookshelf
get /store/add_to_cart/3
Pragmatic Bookshelf
9.1 Iteration D1: Moving the Cart
edit app/views/store/add_to_cart.html.erb
<div class="cart-title">Your Cart</div>
<table>
<%= render(:partial => "cart_item", :collection => @cart.items) %>
<tr class="total-line">
<td colspan="2">Total</td>
<td class="total-cell"><%= number_to_currency(@cart.total_price) %></td>
</tr>
</table>
<%= button_to "Empty cart", :action => :empty_cart %>
edit app/views/store/_cart_item.html.erb
<tr>
<td><%= cart_item.quantity %>×</td>
<td><%=h cart_item.title %></td>
<td class="item-price"><%= number_to_currency(cart_item.price) %></td>
</tr>
cp app/views/store/add_to_cart.html.erb app/views/store/_cart.html.erb
edit app/views/store/_cart.html.erb
<div class="cart-title">Your Cart</div>
<table>
<%= render(:partial => "cart_item", :collection => cart.items) %>
<tr class="total-line">
<td colspan="2">Total</td>
<td class="total-cell"><%= number_to_currency(cart.total_price) %></td>
</tr>
</table>
<%= button_to "Empty cart", :action => :empty_cart %>
edit app/views/layouts/store.html.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Pragprog Books Online Store</title>
<%= stylesheet_link_tag "depot", :media => "all" %>
</head>
<body id="store">
<div id="banner">
<%= image_tag("logo.png") %>
<%= @page_title || "Pragmatic Bookshelf" %>
</div>
<div id="columns">
<div id="side">
<div id="cart">
<%= render(:partial => "cart", :object => @cart) %>
</div>
<a href="http://www....">Home</a><br />
<a href="http://www..../faq">Questions</a><br />
<a href="http://www..../news">News</a><br />
<a href="http://www..../contact">Contact</a><br />
</div>
<div id="main">
<% if flash[:notice] -%>
<div id="notice"><%= flash[:notice] %></div>
<% end -%>
<%= yield :layout %>
</div>
</div>
</body>
</html>
edit app/controllers/store_controller.rb
def index
@products = Product.find_products_for_sale
@cart = find_cart
end
edit public/stylesheets/depot.css
/* Styles for the cart in the sidebar */
#cart, #cart table {
font-size: smaller;
color: white;
}
#cart table {
border-top: 1px dotted #595;
border-bottom: 1px dotted #595;
margin-bottom: 10px;
}
get /store
Pragmatic Bookshelf
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
edit app/controllers/store_controller.rb
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@cart.add_product(product)
redirect_to_index
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
end
edit app/controllers/store_controller.rb
def redirect_to_index(msg = nil)
flash[:notice] = msg if msg
redirect_to :action => 'index'
end
rm app/views/store/add_to_cart.html.erb
get /store/add_to_cart/3
You are being
redirected .
get http://127.0.0.1:3000/store
Pragmatic Bookshelf
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
9.2 Iteration D2: Creating an AJAX-Based Cart
edit app/views/store/index.html.erb
<% form_remote_tag :url => { :action => 'add_to_cart', :id => product } do %>
<%= submit_tag "Add to Cart" %>
<% end %>
edit app/views/layouts/store.html.erb
<html>
<head>
<title>Pragprog Books Online Store</title>
<%= stylesheet_link_tag "depot", :media => "all" %>
<%= javascript_include_tag :defaults %>
</head>
edit app/controllers/store_controller.rb
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@cart.add_product(product)
respond_to do |format|
format.js
end
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
end
edit app/views/store/add_to_cart.js.rjs
page.replace_html("cart", :partial => "cart", :object => @cart)
9.3 Iteration D3: Highlighting Changes
edit app/models/cart.rb
class Cart
attr_reader :items # <wtf linkend="wtf.attr.accessor">attr_reader</wtf>
def initialize
@items = []
end
def add_product(product)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity
else
current_item = CartItem.new(product)
@items << current_item
end
current_item
end
def total_price
@items.sum { |item| item.price }
end
end
edit app/controllers/store_controller.rb
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@current_item = @cart.add_product(product)
respond_to do |format|
format.js
end
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
end
edit app/views/store/_cart_item.html.erb
<% if cart_item == @current_item %>
<tr id="current_item">
<% else %>
<tr>
<% end %>
<td><%= cart_item.quantity %>×</td>
<td><%=h cart_item.title %></td>
<td class="item-price"><%= number_to_currency(cart_item.price) %></td>
</tr>
edit app/views/store/add_to_cart.js.rjs
page.replace_html("cart", :partial => "cart", :object => @cart)
page[:current_item].visual_effect :highlight,
:startcolor => "#88ff88",
:endcolor => "#114411"
9.4 Iteration D4: Hide an Empty Cart
edit app/views/store/add_to_cart.js.rjs
page.replace_html("cart", :partial => "cart", :object => @cart)
page[:cart].visual_effect :blind_down if @cart.total_items == 1
page[:current_item].visual_effect :highlight,
:startcolor => "#88ff88",
:endcolor => "#114411"
edit app/models/cart.rb
class Cart
attr_reader :items # <wtf linkend="wtf.attr.accessor">attr_reader</wtf>
def initialize
@items = []
end
def add_product(product)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity
else
current_item = CartItem.new(product)
@items << current_item
end
current_item
end
def total_price
@items.sum { |item| item.price }
end
def total_items
@items.sum { |item| item.quantity }
end
end
ls -p app
controllers/
helpers/
models/
views/
ls -p app/helpers
application_helper.rb
products_helper.rb
store_helper.rb
edit app/views/layouts/store.html.erb
<% hidden_div_if(@cart.items.empty?, :id => "cart") do %>
<%= render(:partial => "cart", :object => @cart) %>
<% end %>
edit app/helpers/store_helper.rb
module StoreHelper
def hidden_div_if(condition, attributes = {}, &block)
if condition
attributes["style"] = "display: none"
end
content_tag("div", attributes, &block)
end
end
edit app/controllers/store_controller.rb
def empty_cart
session[:cart] = nil
redirect_to_index
end
9.5 Iteration D5: Degrading If Javascript Is Disabled
edit app/controllers/store_controller.rb
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@current_item = @cart.add_product(product)
respond_to do |format|
format.js if request.xhr?
format.html {redirect_to_index}
end
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
end
get /store/empty_cart
You are being
redirected .
get http://127.0.0.1:3000/store
Pragmatic Bookshelf
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
get /store/add_to_cart/3
You are being
redirected .
get http://127.0.0.1:3000/store
Pragmatic Bookshelf
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
10.1 Iteration E1: Capturing an Order
ruby script/generate scaffold order name:string address:text email:string pay_type:string
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/orders
exists app/views/layouts/
exists test/functional/
exists test/unit/
exists public/stylesheets/
create app/views/orders/index.html.erb
create app/views/orders/show.html.erb
create app/views/orders/new.html.erb
create app/views/orders/edit.html.erb
create app/views/layouts/orders.html.erb
identical public/stylesheets/scaffold.css
create app/controllers/orders_controller.rb
create test/functional/orders_controller_test.rb
create app/helpers/orders_helper.rb
route map.resources :orders
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/order.rb
create test/unit/order_test.rb
create test/fixtures/orders.yml
exists db/migrate
create db/migrate/20090515174044_create_orders.rb
ruby script/generate scaffold line_item product_id:integer order_id:integer quantity:integer total_price:decimal
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/line_items
exists app/views/layouts/
exists test/functional/
exists test/unit/
exists public/stylesheets/
create app/views/line_items/index.html.erb
create app/views/line_items/show.html.erb
create app/views/line_items/new.html.erb
create app/views/line_items/edit.html.erb
create app/views/layouts/line_items.html.erb
identical public/stylesheets/scaffold.css
create app/controllers/line_items_controller.rb
create test/functional/line_items_controller_test.rb
create app/helpers/line_items_helper.rb
route map.resources :line_items
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/line_item.rb
create test/unit/line_item_test.rb
create test/fixtures/line_items.yml
exists db/migrate
create db/migrate/20090515174049_create_line_items.rb
edit db/migrate/20090515174044_create_orders.rb
def self.up
create_table :orders do |t|
t.string :name
t.text :address
t.string :email
t.string :pay_type, :limit => 10
t.timestamps
end
end
edit db/migrate/20090515174049_create_line_items.rb
class CreateLineItems < ActiveRecord::Migration
def self.up
create_table :line_items do |t|
t.integer :product_id, :null => false, :options =>
"CONSTRAINT fk_line_item_products REFERENCES products(id)"
t.integer :order_id, :null => false, :options =>
"CONSTRAINT fk_line_item_orders REFERENCES orders(id)"
t.integer :quantity, :null => false
t.decimal :total_price, :null => false, :precision => 8, :scale => 2
t.timestamps
end
end
def self.down
drop_table :line_items
end
end
rake db:migrate
mv 20090515174044_create_orders.rb 20080601000005_create_orders.rb
mv 20090515174049_create_line_items.rb 20080601000006_create_line_items.rb
(in /Users/rubys/git/awdwr/work/depot)
== CreateOrders: migrating ===================================================
-- create_table(:orders)
-> 0.0157s
== CreateOrders: migrated (0.0159s) ==========================================
== CreateLineItems: migrating ================================================
-- create_table(:line_items)
-> 0.0044s
== CreateLineItems: migrated (0.0046s) =======================================
sqlite3 db/development.sqlite3 .schema
CREATE TABLE "line_items" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "product_id" integer NOT NULL, "order_id" integer NOT NULL, "quantity" integer NOT NULL, "total_price" decimal(8,2) NOT NULL, "created_at" datetime, "updated_at" datetime);
CREATE TABLE "orders" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "address" text, "email" varchar(255), "pay_type" varchar(10), "created_at" datetime, "updated_at" datetime);
CREATE TABLE "products" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "description" text, "image_url" varchar(255), "created_at" datetime, "updated_at" datetime, "price" decimal(8,2) DEFAULT 0);
CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);
CREATE TABLE "sessions" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "session_id" varchar(255) NOT NULL, "data" text, "created_at" datetime, "updated_at" datetime);
CREATE INDEX "index_sessions_on_session_id" ON "sessions" ("session_id");
CREATE INDEX "index_sessions_on_updated_at" ON "sessions" ("updated_at");
CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version");
edit app/models/order.rb
class Order < ActiveRecord::Base
has_many :line_items
end
edit app/models/product.rb
class Product < ActiveRecord::Base
has_many :line_items
# ...
edit app/models/line_item.rb
class LineItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
end
edit app/views/store/_cart.html.erb
<div class="cart-title">Your Cart</div>
<table>
<%= render(:partial => "cart_item", :collection => cart.items) %>
<tr class="total-line">
<td colspan="2">Total</td>
<td class="total-cell"><%= number_to_currency(cart.total_price) %></td>
</tr>
</table>
<%= button_to "Checkout", :action => 'checkout' %>
<%= button_to "Empty cart", :action => :empty_cart %>
edit app/controllers/store_controller.rb
def checkout
@cart = find_cart
if @cart.items.empty?
redirect_to_index("Your cart is empty")
else
@order = Order.new
end
end
edit app/views/store/checkout.html.erb
<div class="depot-form">
<%= error_messages_for 'order' %>
<% form_for :order, :url => { :action => :save_order } do |form| %>
<fieldset>
<legend>Please Enter Your Details</legend>
<div>
<%= form.label :name, "Name:" %>
<%= form.text_field :name, :size => 40 %>
</div>
<div>
<%= form.label :address, "Address:" %>
<%= form.text_area :address, :rows => 3, :cols => 40 %>
</div>
<div>
<%= form.label :email, "E-Mail:" %>
<%= form.text_field :email, :size => 40 %>
</div>
<div>
<%= form.label :pay_type, "Pay with:" %>
<%=
form.select :pay_type,
Order::PAYMENT_TYPES,
:prompt => "Select a payment method"
%>
</div>
<%= submit_tag "Place Order", :class => "submit" %>
</fieldset>
<% end %>
</div>
edit app/models/order.rb
class Order < ActiveRecord::Base
PAYMENT_TYPES = [
# Displayed stored in db
[ "Check", "check" ],
[ "Credit card", "cc" ],
[ "Purchase order", "po" ]
]
# ...
edit public/stylesheets/depot.css
/* Styles for order form */
.depot-form fieldset {
background: #efe;
}
.depot-form legend {
color: #dfd;
background: #141;
font-family: sans-serif;
padding: 0.2em 1em;
}
.depot-form label {
width: 5em;
float: left;
text-align: right;
padding-top: 0.2em;
margin-right: 0.1em;
display: block;
}
.depot-form select, .depot-form textarea, .depot-form input {
margin-left: 0.5em;
}
.depot-form .submit {
margin-left: 4em;
}
.depot-form div {
margin: 0.5em 0;
}
get /store/checkout
Pragmatic Bookshelf
get /store/save_order
Unknown action
No action responded to save_order. Actions: add_to_cart, checkout, empty_cart, and index
edit app/models/order.rb
class Order < ActiveRecord::Base
PAYMENT_TYPES = [
# Displayed stored in db
[ "Check", "check" ],
[ "Credit card", "cc" ],
[ "Purchase order", "po" ]
]
validates_presence_of :name, :address, :email, :pay_type
validates_inclusion_of :pay_type, :in =>
PAYMENT_TYPES.map {|disp, value| value}
# ...
edit app/controllers/store_controller.rb
def save_order
@cart = find_cart
@order = Order.new(params[:order]) # <label id="code.p.new.order"/>
@order.add_line_items_from_cart(@cart) # <label id="code.p.append.li"/>
if @order.save # <label id="code.p.save"/>
session[:cart] = nil
redirect_to_index("Thank you for your order")
else
render :action => 'checkout'
end
end
edit app/models/order.rb
class Order < ActiveRecord::Base
PAYMENT_TYPES = [
# Displayed stored in db
[ "Check", "check" ],
[ "Credit card", "cc" ],
[ "Purchase order", "po" ]
]
# ...
validates_presence_of :name, :address, :email, :pay_type
validates_inclusion_of :pay_type, :in =>
PAYMENT_TYPES.map {|disp, value| value}
# ...
has_many :line_items
def add_line_items_from_cart(cart)
cart.items.each do |item|
li = LineItem.from_cart_item(item)
line_items << li
end
end
end
edit app/models/line_item.rb
class LineItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
def self.from_cart_item(cart_item)
li = self.new
li.product = cart_item.product
li.quantity = cart_item.quantity
li.total_price = cart_item.price
li
end
end
sqlite3> select * from orders
sqlite3> select * from line_items
get /store/save_order
Pragmatic Bookshelf
get /store/checkout
Pragmatic Bookshelf
post /store/save_order
order[pay_type] => check
order[address] => 123 Main St
order[email] => customer@pragprog.com
order[name] => Dave Thomas
You are being
redirected .
get http://127.0.0.1:3000/store
Pragmatic Bookshelf
Thank you for your order
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
sqlite3> select * from orders
id = 1
name = Dave Thomas
address = 123 Main St
email = customer@pragprog.com
pay_type = check
created_at = 2009-05-15 17:41:00
updated_at = 2009-05-15 17:41:00
sqlite3> select * from line_items
id = 1
product_id = 3
order_id = 1
quantity = 1
total_price = 28.5
created_at = 2009-05-15 17:41:00
updated_at = 2009-05-15 17:41:00
edit app/views/store/add_to_cart.js.rjs
page.select("div#notice").each { |div| div.hide }
page.replace_html("cart", :partial => "cart", :object => @cart)
page[:cart].visual_effect :blind_down if @cart.total_items == 1
page[:current_item].visual_effect :highlight,
:startcolor => "#88ff88",
:endcolor => "#114411"
11.1 Iteration F1: Adding Users
ruby script/generate scaffold user name:string hashed_password:string salt:string
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/users
exists app/views/layouts/
exists test/functional/
exists test/unit/
exists public/stylesheets/
create app/views/users/index.html.erb
create app/views/users/show.html.erb
create app/views/users/new.html.erb
create app/views/users/edit.html.erb
create app/views/layouts/users.html.erb
identical public/stylesheets/scaffold.css
create app/controllers/users_controller.rb
create test/functional/users_controller_test.rb
create app/helpers/users_helper.rb
route map.resources :users
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/user.rb
create test/unit/user_test.rb
create test/fixtures/users.yml
exists db/migrate
create db/migrate/20090515174107_create_users.rb
restart
cat db/migrate/20090515174107_create_users.rb
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.string :hashed_password
t.string :salt
t.timestamps
end
end
def self.down
drop_table :users
end
end
rake db:migrate
mv 20090515174107_create_users.rb 20080601000007_create_users.rb
(in /Users/rubys/git/awdwr/work/depot)
== CreateUsers: migrating ====================================================
-- create_table(:users)
-> 0.0160s
== CreateUsers: migrated (0.0163s) ===========================================
edit app/models/user.rb
require 'digest/sha1'
class User < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
attr_accessor :password_confirmation
validates_confirmation_of :password
validate :password_non_blank
def self.authenticate(name, password)
user = self.find_by_name(name)
if user
expected_password = encrypted_password(password, user.salt)
if user.hashed_password != expected_password
user = nil
end
end
user
end
# 'password' is a virtual attribute
def password
@password
end
def password=(pwd)
@password = pwd
return if pwd.blank?
create_new_salt
self.hashed_password = User.encrypted_password(self.password, self.salt)
end
private
def password_non_blank
errors.add(:password, "Missing password") if hashed_password.blank?
end
def create_new_salt
self.salt = self.object_id.to_s + rand.to_s
end
def self.encrypted_password(password, salt)
string_to_hash = password + "wibble" + salt
Digest::SHA1.hexdigest(string_to_hash)
end
end
edit app/controllers/users_controller.rb
class UsersController < ApplicationController
# GET /users
# GET /users.xml
def index
@users = User.find(:all, :order => :name)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
end
end
# GET /users/1
# GET /users/1.xml
def show
@user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @user }
end
end
# GET /users/new
# GET /users/new.xml
def new
@user = User.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @user }
end
end
# GET /users/1/edit
def edit
@user = User.find(params[:id])
end
# POST /users
# POST /users.xml
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
flash[:notice] = "User #{@user.name} was successfully created."
format.html { redirect_to(:action=>'index') }
format.xml { render :xml => @user, :status => :created,
:location => @user }
else
format.html { render :action => "new" }
format.xml { render :xml => @user.errors,
:status => :unprocessable_entity }
end
end
end
# PUT /users/1
# PUT /users/1.xml
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
flash[:notice] = "User #{@user.name} was successfully updated."
format.html { redirect_to(:action=>'index') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @user.errors,
:status => :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.xml
def destroy
@user = User.find(params[:id])
@user.destroy
respond_to do |format|
format.html { redirect_to(users_url) }
format.xml { head :ok }
end
end
end
edit app/views/users/index.html.erb
<h1>Listing users</h1>
<table>
<tr>
<th>Name</th>
</tr>
<% for user in @users %>
<tr>
<td><%=h user.name %></td>
<td><%= link_to 'Show', user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<td><%= link_to 'Destroy', user, :confirm => 'Are you sure?',
:method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New user', new_user_path %>
edit app/views/users/new.html.erb
<div class="depot-form">
<% form_for(@user) do |f| %>
<%= f.error_messages %>
<fieldset>
<legend>Enter User Details</legend>
<div>
<%= f.label :name %>:
<%= f.text_field :name, :size => 40 %>
</div>
<div>
<%= f.label :password, 'Password' %>:
<%= f.password_field :password, :size => 40 %>
</div>
<div>
<%= f.label :password_confirmation, 'Confirm' %>:
<%= f.password_field :password_confirmation, :size => 40 %>
</div>
<div>
<%= f.submit "Add User", :class => "submit" %>
</div>
</fieldset>
<% end %>
</div>
edit app/views/layouts/users.html.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Users: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold', 'depot' %>
</head>
get /users
get /users/new
post /users
user[password_confirmation] => secret
user[name] => dave
user[password] => secret
You are being
redirected .
get http://127.0.0.1:3000/users
User dave was successfully created.
Listing users
New user
sqlite3> select * from users
id = 1
name = dave
hashed_password = 54b58daf9bf0c9e565081eba0f1fa943fa61349b
salt = 198709100.76596880410962
created_at = 2009-05-15 17:41:19
updated_at = 2009-05-15 17:41:19
11.2 Iteration F2: Logging in
ruby script/generate controller admin login logout index
exists app/controllers/
exists app/helpers/
create app/views/admin
exists test/functional/
create app/controllers/admin_controller.rb
create test/functional/admin_controller_test.rb
create app/helpers/admin_helper.rb
create app/views/admin/login.html.erb
create app/views/admin/logout.html.erb
create app/views/admin/index.html.erb
restart
edit app/controllers/admin_controller.rb
class AdminController < ApplicationController
# just display the form and wait for user to
# enter a name and password
def login
if request.post?
user = User.authenticate(params[:name], params[:password])
if user
session[:user_id] = user.id
redirect_to(:action => "index")
else
flash.now[:notice] = "Invalid user/password combination"
end
end
end
def logout
session[:user_id] = nil
flash[:notice] = "Logged out"
redirect_to(:action => "login")
end
def index
@total_orders = Order.count
end
end
edit app/views/admin/login.html.erb
<div class="depot-form">
<% form_tag do %>
<fieldset>
<legend>Please Log In</legend>
<div>
<label for="name">Name:</label>
<%= text_field_tag :name, params[:name] %>
</div>
<div>
<label for="password">Password:</label>
<%= password_field_tag :password, params[:password] %>
</div>
<div>
<%= submit_tag "Login" %>
</div>
</fieldset>
<% end %>
</div>
edit app/views/admin/index.html.erb
<h1>Welcome</h1>
It's <%= Time.now %>
We have <%= pluralize(@total_orders, "order") %>.
get /admin/login
post /admin/login
name => dave
password => secret
You are being
redirected .
get http://127.0.0.1:3000/admin
Welcome
It's Fri May 15 13:41:31 -0400 2009
We have 1 order.
11.3 Iteration F3: Limiting Access
edit app/controllers/application.rb
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
before_filter :authorize, :except => :login
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery :secret => '156f9e3d5ab2773114a2ec10be357e0a'
# See ActionController::Base for details
# Uncomment this to filter the contents of submitted sensitive data parameters
# from your application log (in this case, all fields with names like "password").
# filter_parameter_logging :password
protected
def authorize
unless User.find_by_id(session[:user_id])
flash[:notice] = "Please log in"
redirect_to :controller => 'admin', :action => 'login'
end
end
end
edit app/controllers/store_controller.rb
class StoreController < ApplicationController
def index
@products = Product.find_products_for_sale
@cart = find_cart
end
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@current_item = @cart.add_product(product)
respond_to do |format|
format.js if request.xhr?
format.html {redirect_to_index}
end
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
end
def checkout
@cart = find_cart
if @cart.items.empty?
redirect_to_index("Your cart is empty")
else
@order = Order.new
end
end
def save_order
@cart = find_cart
@order = Order.new(params[:order])
@order.add_line_items_from_cart(@cart)
if @order.save
session[:cart] = nil
redirect_to_index("Thank you for your order")
else
render :action => 'checkout'
end
end
def empty_cart
session[:cart] = nil
redirect_to_index
end
private
def redirect_to_index(msg = nil)
flash[:notice] = msg if msg
redirect_to :action => 'index'
end
def find_cart
session[:cart] ||= Cart.new
end
end
edit app/controllers/store_controller.rb
class StoreController < ApplicationController
#...
protected
def authorize
end
end
rake db:sessions:clear
(in /Users/rubys/git/awdwr/work/depot)
get /admin/logout
You are being
redirected .
get http://127.0.0.1:3000/admin/login
get /store
Pragmatic Bookshelf
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
get /products
You are being
redirected .
get http://127.0.0.1:3000/admin/login
get /admin/login
post /admin/login
name => dave
password => secret
You are being
redirected .
get http://127.0.0.1:3000/admin
Welcome
It's Fri May 15 13:41:40 -0400 2009
We have 1 order.
get /products
11.4 Iteration F4: Adding a Sidebar, More Administration
edit app/controllers/application.rb
class ApplicationController < ActionController::Base
layout "store"
#...
get /admin
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Action Controller: Exception caught</title>
<style>
body { background-color: #fff; color: #333; }
body, p, ol, ul, td {
font-family: verdana, arial, helvetica, sans-serif;
font-size: 13px;
line-height: 18px;
}
pre {
background-color: #eee;
padding: 10px;
font-size: 11px;
}
a { color: #000; }
a:visited { color: #666; }
a:hover { color: #fff; background-color:#000; }
</style>
</head>
<body>
<h1>
NoMethodError in
Admin#index
</h1>
<p>
Showing <i>app/views/layouts/store.html.erb</i> where line <b>#24</b> raised:
<pre><code>You have a nil object when you didn't expect it!
The error occurred while evaluating nil.items</code></pre>
</p>
<p>Extracted source (around line <b>#24</b>):
<pre><code>21: <div id="side">
22: <!-- START_HIGHLIGHT -->
23: <!-- START:hidden_div -->
24: <% hidden_div_if(@cart.items.empty?, :id => "cart") do %>
25: <%= render(:partial => "cart", :object => @cart) %>
26: <% end %>
27: <!-- END:hidden_div -->
</code></pre></p>
<p></p>
<p><code>RAILS_ROOT: /Users/rubys/git/awdwr/work/depot</code></p>
<div id="traces">
<a href="#" onclick="document.getElementById('Framework-Trace').style.display='none';document.getElementById('Full-Trace').style.display='none';document.getElementById('Application-Trace').style.display='block';; return false;">Application Trace</a> |
<a href="#" onclick="document.getElementById('Application-Trace').style.display='none';document.getElementById('Full-Trace').style.display='none';document.getElementById('Framework-Trace').style.display='block';; return false;">Framework Trace</a> |
<a href="#" onclick="document.getElementById('Application-Trace').style.display='none';document.getElementById('Framework-Trace').style.display='none';document.getElementById('Full-Trace').style.display='block';; return false;">Full Trace</a>
<div id="Application-Trace" style="display: block;">
<pre><code>app/views/layouts/store.html.erb:24
makedepot.rb:2300:in `restart_server'
makedepot.rb:999
makedepot.rb:2374:in `call'
makedepot.rb:2374
makedepot.rb:2371:in `each'
makedepot.rb:2371
makedepot.rb:2334
makedepot.rb:2307</code></pre>
</div>
<div id="Framework-Trace" style="display: none;">
<pre><code>/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/renderable.rb:39:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/renderable.rb:39:in `render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/template.rb:73:in `render_template'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/base.rb:256:in `render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/base.rb:371:in `_render_with_layout'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/base.rb:254:in `render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1174:in `render_for_file'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:896:in `render_without_benchmark'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:51:in `render'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/core_ext/benchmark.rb:8:in `realtime'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:51:in `render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:868:in `render_without_benchmark'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:51:in `render'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/core_ext/benchmark.rb:8:in `realtime'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:51:in `render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1248:in `default_render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1254:in `perform_action_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:617:in `call_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:610:in `perform_action_without_benchmark'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/1.8/benchmark.rb:293:in `measure'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/rescue.rb:136:in `perform_action_without_caching'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:13:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/query_cache.rb:34:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/query_cache.rb:8:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:12:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `process_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:606:in `process_without_session_management_support'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/session_management.rb:134:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:392:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:183:in `handle_request'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:110:in `dispatch_unlocked'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:123:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:132:in `dispatch_cgi'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:39:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:76:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:159:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:282:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:128:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/command.rb:212:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load_without_new_constant_marking'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/servers/mongrel.rb:64
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/server.rb:49
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'</code></pre>
</div>
<div id="Full-Trace" style="display: none;">
<pre><code>app/views/layouts/store.html.erb:24
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/renderable.rb:39:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/renderable.rb:39:in `render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/template.rb:73:in `render_template'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/base.rb:256:in `render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/base.rb:371:in `_render_with_layout'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_view/base.rb:254:in `render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1174:in `render_for_file'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:896:in `render_without_benchmark'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:51:in `render'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/core_ext/benchmark.rb:8:in `realtime'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:51:in `render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:868:in `render_without_benchmark'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:51:in `render'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/core_ext/benchmark.rb:8:in `realtime'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:51:in `render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1248:in `default_render'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:1254:in `perform_action_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:617:in `call_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:610:in `perform_action_without_benchmark'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/1.8/benchmark.rb:293:in `measure'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/rescue.rb:136:in `perform_action_without_caching'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:13:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/query_cache.rb:34:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/query_cache.rb:8:in `cache'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/caching/sql_cache.rb:12:in `perform_action'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `send'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:524:in `process_without_filters'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:606:in `process_without_session_management_support'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/session_management.rb:134:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/base.rb:392:in `process'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:183:in `handle_request'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:110:in `dispatch_unlocked'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:123:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:122:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:132:in `dispatch_cgi'
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/dispatcher.rb:39:in `dispatch'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:76:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `synchronize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/rails.rb:74:in `process'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:159:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:158:in `process_client'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:285:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `initialize'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `new'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb:268:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:282:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `each'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/configurator.rb:281:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:128:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel/command.rb:212:in `run'
/opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/mongrel_rails:281
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load_without_new_constant_marking'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:142:in `load'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/servers/mongrel.rb:64
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:521:in `new_constants_in'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'
/opt/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/server.rb:49
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/opt/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
makedepot.rb:2300:in `restart_server'
makedepot.rb:999
makedepot.rb:2374:in `call'
makedepot.rb:2374
makedepot.rb:2371:in `each'
makedepot.rb:2371
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
makedepot.rb:2334
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/opt/local/lib/ruby/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
makedepot.rb:2307</code></pre>
</div>
</div>
<h2 style="margin-top: 30px">Request</h2>
<p><b>Parameters</b>: <pre>None</pre></p>
<p><a href="#" onclick="document.getElementById('session_dump').style.display='block'; return false;">Show session dump</a></p>
<div id="session_dump" style="display:none"><pre class='debug_dump'>---
:user_id: 1
flash: !map:ActionController::Flash::FlashHash {}
:cart: !ruby/object:Cart
items: []
</pre></div>
<h2 style="margin-top: 30px">Response</h2>
<p><b>Headers</b>: <pre>{"Content-Type"=>"text/html",
"cookie"=>[],
"Cache-Control"=>"no-cache"}</pre></p>
</body>
</html>
get /users
edit app/views/layouts/store.html.erb
<% if @cart %>
<% hidden_div_if(@cart.items.empty?, :id => "cart") do %>
<%= render(:partial => "cart", :object => @cart) %>
<% end %>
<% end %>
get /admin
Pragmatic Bookshelf
Welcome
It's Fri May 15 13:41:43 -0400 2009
We have 1 order.
get /users
rm app/views/layouts/products.html.erb
rm app/views/layouts/users.html.erb
rm app/views/layouts/orders.html.erb
get /users
Pragmatic Bookshelf
edit app/models/user.rb
require 'digest/sha1'
class User < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
attr_accessor :password_confirmation
validates_confirmation_of :password
validate :password_non_blank
def self.authenticate(name, password)
user = self.find_by_name(name)
if user
expected_password = encrypted_password(password, user.salt)
if user.hashed_password != expected_password
user = nil
end
end
user
end
# 'password' is a virtual attribute
def password
@password
end
def password=(pwd)
@password = pwd
return if pwd.blank?
create_new_salt
self.hashed_password = User.encrypted_password(self.password, self.salt)
end
def after_destroy
if User.count.zero?
raise "Can't delete last user"
end
end
private
def password_non_blank
errors.add(:password, "Missing password") if hashed_password.blank?
end
def create_new_salt
self.salt = self.object_id.to_s + rand.to_s
end
def self.encrypted_password(password, salt)
string_to_hash = password + "wibble" + salt
Digest::SHA1.hexdigest(string_to_hash)
end
end
edit app/controllers/users_controller.rb
class UsersController < ApplicationController
# GET /users
# GET /users.xml
def index
@users = User.find(:all, :order => :name)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
end
end
# GET /users/1
# GET /users/1.xml
def show
@user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @user }
end
end
# GET /users/new
# GET /users/new.xml
def new
@user = User.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @user }
end
end
# GET /users/1/edit
def edit
@user = User.find(params[:id])
end
# POST /users
# POST /users.xml
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
flash[:notice] = "User #{@user.name} was successfully created."
format.html { redirect_to(:action=>'index') }
format.xml { render :xml => @user, :status => :created,
:location => @user }
else
format.html { render :action => "new" }
format.xml { render :xml => @user.errors,
:status => :unprocessable_entity }
end
end
end
# PUT /users/1
# PUT /users/1.xml
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
flash[:notice] = "User #{@user.name} was successfully updated."
format.html { redirect_to(:action=>'index') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @user.errors,
:status => :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.xml
def destroy
@user = User.find(params[:id])
begin
@user.destroy
flash[:notice] = "User #{@user.name} deleted"
rescue Exception => e
flash[:notice] = e.message
end
respond_to do |format|
format.html { redirect_to(users_url) }
format.xml { head :ok }
end
end
end
edit app/controllers/store_controller.rb
def find_cart
@cart = (session[:cart] ||= Cart.new)
end
edit app/controllers/store_controller.rb
before_filter :find_cart, :except => :empty_cart
echo "Product.new" | ruby script/console
>> Product.new
=> #<Product id: nil, title: nil, description: nil, image_url: nil, created_at: nil, updated_at: nil, price: #<BigDecimal:24bc8e4,'0.0',4(8)>>
>>
12.1 Generating the XML Feed
edit app/models/product.rb
class Product < ActiveRecord::Base
has_many :orders, :through => :line_items
has_many :line_items
# ...
ruby script/generate controller info who_bought
exists app/controllers/
exists app/helpers/
create app/views/info
exists test/functional/
create app/controllers/info_controller.rb
create test/functional/info_controller_test.rb
create app/helpers/info_helper.rb
create app/views/info/who_bought.html.erb
edit app/controllers/info_controller.rb
class InfoController < ApplicationController
def who_bought
@product = Product.find(params[:id])
@orders = @product.orders
respond_to do |format|
format.xml { render :layout => false }
end
end
protected
def authorize
end
end
edit app/views/info/who_bought.xml.builder
xml.order_list(:for_product => @product.title) do
for o in @orders
xml.order do
xml.name(o.name)
xml.email(o.email)
end
end
end
curl --silent http://localhost:3000/info/who_bought/3
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Action Controller: Exception caught</title>
<style>
body { background-color: #fff; color: #333; }
body, p, ol, ul, td {
font-family: verdana, arial, helvetica, sans-serif;
font-size: 13px;
line-height: 18px;
}
pre {
background-color: #eee;
padding: 10px;
font-size: 11px;
}
a { color: #000; }
a:visited { color: #666; }
a:hover { color: #fff; background-color:#000; }
</style>
</head>
<body>
<h1>Routing Error</h1>
<p><pre>No route matches "/info/who_bought/3" with {:method=>:get}</pre></p>
</body>
</html>
restart
curl --silent http://localhost:3000/info/who_bought/3
<order_list for_product="Pragmatic Version Control">
<order>
<name>Dave Thomas</name>
<email>customer@pragprog.com</email>
</order>
</order_list>
sqlite3> select * from products
id = 2
title = Pragmatic Project Automation
description = <p>
<em>Pragmatic Project Automation</em> shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
</p>
<p>
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
</p>
image_url = /images/auto.jpg
created_at = 2009-05-15 17:39:48
updated_at = 2009-05-15 17:39:48
price = 29.95
id = 3
title = Pragmatic Version Control
description = <p>
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
</p>
image_url = /images/svn.jpg
created_at = 2009-05-15 17:39:48
updated_at = 2009-05-15 17:39:48
price = 28.5
id = 4
title = Pragmatic Unit Testing (C#)
description = <p>
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
</p>
<p>
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
</p>
image_url = /images/utc.jpg
created_at = 2009-05-15 17:39:48
updated_at = 2009-05-15 17:39:48
price = 27.75
sqlite3> select * from line_items
id = 1
product_id = 3
order_id = 1
quantity = 1
total_price = 28.5
created_at = 2009-05-15 17:41:00
updated_at = 2009-05-15 17:41:00
curl --silent http://localhost:3000/info/who_bought/3
<order_list for_product="Pragmatic Version Control">
<order>
<name>Dave Thomas</name>
<email>customer@pragprog.com</email>
</order>
</order_list>
edit app/views/info/who_bought.html.erb
<h3>People Who Bought <%= @product.title %></h3>
<ul>
<% for order in @orders -%>
<li>
<%= mail_to order.email, order.name %>
</li>
<% end -%>
</ul>
edit app/controllers/info_controller.rb
class InfoController < ApplicationController
def who_bought
@product = Product.find(params[:id])
@orders = @product.orders
respond_to do |format|
format.html
format.xml { render :layout => false }
end
end
protected
def authorize
end
end
curl --silent -H "Accept: text/html" http://localhost:3000/info/who_bought/3
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- START:jit -->
<html>
<head>
<title>Pragprog Books Online Store</title>
<!-- START:stylesheet -->
<link href="/stylesheets/depot.css?1242409254" media="all" rel="stylesheet" type="text/css" />
<!-- END:stylesheet -->
<script src="/javascripts/prototype.js?1242409120" type="text/javascript"></script>
<script src="/javascripts/effects.js?1242409120" type="text/javascript"></script>
<script src="/javascripts/dragdrop.js?1242409120" type="text/javascript"></script>
<script src="/javascripts/controls.js?1242409120" type="text/javascript"></script>
<script src="/javascripts/application.js?1242409120" type="text/javascript"></script>
</head>
<!-- END:jit -->
<body id="store">
<div id="banner">
<img alt="Logo" src="/images/logo.png?1242409188" />
Pragmatic Bookshelf
</div>
<div id="columns">
<div id="side">
<!-- START:hidden_div -->
<!-- START_HIGHLIGHT -->
<!-- END_HIGHLIGHT -->
<!-- END:hidden_div -->
<a href="http://www....">Home</a><br />
<a href="http://www..../faq">Questions</a><br />
<a href="http://www..../news">News</a><br />
<a href="http://www..../contact">Contact</a><br />
<!-- START_HIGHLIGHT -->
<!-- END_HIGHLIGHT -->
</div>
<div id="main">
<!-- START:flash -->
<!-- END:flash -->
<h3>People Who Bought Pragmatic Version Control</h3>
<ul>
<li>
<a href="mailto:customer@pragprog.com">Dave Thomas</a>
</li>
</ul>
</div>
</div>
</body>
</html>
curl --silent -H "Accept: application/xml" http://localhost:3000/info/who_bought/3
<order_list for_product="Pragmatic Version Control">
<order>
<name>Dave Thomas</name>
<email>customer@pragprog.com</email>
</order>
</order_list>
cp app/controllers/info_controller.rb app/controllers/info_controller.save
edit app/controllers/info_controller.rb
class InfoController < ApplicationController
def who_bought
@product = Product.find(params[:id])
@orders = @product.orders
respond_to do |format|
format.html
format.xml { render :layout => false ,
:xml => @product.to_xml(:include => :orders) }
end
end
protected
def authorize
end
end
curl --silent http://localhost:3000/info/who_bought/3.xml
<?xml version="1.0" encoding="UTF-8"?>
<product>
<created-at type="datetime">2009-05-15T17:39:48Z</created-at>
<description><p>
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
</p></description>
<id type="integer">3</id>
<image-url>/images/svn.jpg</image-url>
<price type="decimal">28.5</price>
<title>Pragmatic Version Control</title>
<updated-at type="datetime">2009-05-15T17:39:48Z</updated-at>
<orders type="array">
<order>
<address>123 Main St</address>
<created-at type="datetime">2009-05-15T17:41:00Z</created-at>
<email>customer@pragprog.com</email>
<id type="integer">1</id>
<name>Dave Thomas</name>
<pay-type>check</pay-type>
<updated-at type="datetime">2009-05-15T17:41:00Z</updated-at>
</order>
</orders>
</product>
edit app/views/info/who_bought.atom.builder
atom_feed do |feed|
feed.title "Who bought #{@product.title}"
feed.updated @orders.first.created_at
for order in @orders
feed.entry(order) do |entry|
entry.title "Order #{order.id}"
entry.summary :type => 'xhtml' do |xhtml|
xhtml.p "Shipped to #{order.address}"
xhtml.table do
xhtml.tr do
xhtml.th 'Product'
xhtml.th 'Quantity'
xhtml.th 'Total Price'
end
for item in order.line_items
xhtml.tr do
xhtml.td item.product.title
xhtml.td item.quantity
xhtml.td number_to_currency item.total_price
end
end
xhtml.tr do
xhtml.th 'total', :colspan => 2
xhtml.th number_to_currency \
order.line_items.map(&:total_price).sum
end
end
xhtml.p "Paid by #{order.pay_type}"
end
entry.author do |author|
entry.name order.name
entry.email order.email
end
end
end
end
edit app/controllers/info_controller.rb
class InfoController < ApplicationController
def who_bought
@product = Product.find(params[:id])
@orders = @product.orders
respond_to do |format|
format.html
format.atom { render :layout => false }
format.xml { render :layout => false ,
:xml => @product.to_xml(:include => :orders) }
end
end
protected
def authorize
end
end
curl --silent http://localhost:3000/info/who_bought/3.atom
<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
<id>tag:localhost,2005:/info/who_bought/3</id>
<link type="text/html" href="http://localhost:3000" rel="alternate"/>
<link type="application/atom+xml" href="http://localhost:3000/info/who_bought/3.atom" rel="self"/>
<title>Who bought Pragmatic Version Control</title>
<updated>2009-05-15T17:41:00Z</updated>
<entry>
<id>tag:localhost,2005:Order/1</id>
<published>2009-05-15T17:41:00Z</published>
<updated>2009-05-15T17:41:00Z</updated>
<link type="text/html" href="http://localhost:3000/orders/1" rel="alternate"/>
<title>Order 1</title>
<summary type="xhtml">
<div xmlns="http://www.w3.org/1999/xhtml">
<p>Shipped to 123 Main St</p>
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Total Price</th>
</tr>
<tr>
<td>Pragmatic Version Control</td>
<td>1</td>
<td>$28.50</td>
</tr>
<tr>
<th colspan="2">total</th>
<th>$28.50</th>
</tr>
</table>
<p>Paid by check</p>
</div>
</summary>
<author>
<name>Dave Thomas</name>
<email>customer@pragprog.com</email>
</author>
</entry>
</feed>
edit app/controllers/info_controller.rb
class InfoController < ApplicationController
def who_bought
@product = Product.find(params[:id])
@orders = @product.orders
respond_to do |format|
format.html
format.atom { render :layout => false }
format.xml { render :layout => false ,
:xml => @product.to_xml(:include => :orders) }
format.json { render :layout => false ,
:json => @product.to_json(:include => :orders) }
end
end
protected
def authorize
end
end
curl --silent -H "Accept: application/json" http://localhost:3000/info/who_bought/3
{"product": {"price": 28.5, "created_at": "2009-05-15T17:39:48Z", "title": "Pragmatic Version Control", "image_url": "/images/svn.jpg", "updated_at": "2009-05-15T17:39:48Z", "id": 3, "orders": [{"name": "Dave Thomas", "address": "123 Main St", "created_at": "2009-05-15T17:41:00Z", "updated_at": "2009-05-15T17:41:00Z", "pay_type": "check", "id": 1, "email": "customer@pragprog.com"}], "description": "<p>\n This book is a recipe-based approach to using Subversion that will \n get you up and running quickly---and correctly. All projects need\n version control: it's a foundational piece of any project's \n infrastructure. Yet half of all project teams in the U.S. don't use\n any version control at all. Many others don't use it well, and end \n up experiencing time-consuming problems.\n </p>"}}
mv app/controllers/info_controller.save app/controllers/info_controller.rb
rake doc:app
rm -r doc/app
README_FOR_APP:
admin_controller.rb: c...
application.rb: c.
info_controller.rb: c..
line_items_controller.rb: c.......
orders_controller.rb: c.......
products_controller.rb: c.......
store_controller.rb: c........
users_controller.rb: c.......
admin_helper.rb: m
application_helper.rb: m
info_helper.rb: m
line_items_helper.rb: m
orders_helper.rb: m
products_helper.rb: m
store_helper.rb: m.
users_helper.rb: m
cart.rb: c....
cart_item.rb: c....
line_item.rb: c.
order.rb: c.
product.rb: c..
user.rb: c.......
Generating HTML...
(in /Users/rubys/git/awdwr/work/depot)
Files: 23
Classes: 14
Modules: 8
Methods: 62
Elapsed: 2.763s
rake stats
(in /Users/rubys/git/awdwr/work/depot)
+----------------------+-------+-------+---------+---------+-----+-------+
| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |
+----------------------+-------+-------+---------+---------+-----+-------+
| Controllers | 521 | 344 | 8 | 42 | 5 | 6 |
| Helpers | 23 | 22 | 0 | 1 | 0 | 20 |
| Models | 229 | 129 | 6 | 19 | 3 | 4 |
| Libraries | 0 | 0 | 0 | 0 | 0 | 0 |
| Integration tests | 0 | 0 | 0 | 0 | 0 | 0 |
| Functional tests | 204 | 162 | 7 | 0 | 0 | 0 |
| Unit tests | 32 | 24 | 4 | 0 | 0 | 0 |
+----------------------+-------+-------+---------+---------+-----+-------+
| Total | 1009 | 681 | 25 | 62 | 2 | 8 |
+----------------------+-------+-------+---------+---------+-----+-------+
Code LOC: 495 Test LOC: 186 Code to Test Ratio: 1:0.4
13 Task I: Internationalization
get /store/empty_cart
You are being
redirected .
get http://127.0.0.1:3000/store
Pragmatic Bookshelf
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
cp /Users/rubys/git/awdwr/data/i18n/initializer.rb config/initializers/i18n.rb
restart
edit app/views/layouts/store.html.erb
<% form_tag '', :method => 'GET', :class => 'locale' do %>
<%= select_tag 'locale', options_for_select(LANGUAGES, I18n.locale),
:onchange => 'this.form.submit()' %>
<%= submit_tag 'submit' %>
<%= javascript_tag "$$('.locale input').each(Element.hide)" %>
<% end %>
get /store?locale=en
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
edit app/controllers/application.rb
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
layout "store"
#...
before_filter :authorize, :except => :login
before_filter :set_locale
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery :secret => '156f9e3d5ab2773114a2ec10be357e0a'
# See ActionController::Base for details
# Uncomment this to filter the contents of submitted sensitive data parameters
# from your application log (in this case, all fields with names like "password").
# filter_parameter_logging :password
protected
def authorize
unless User.find_by_id(session[:user_id])
flash[:notice] = "Please log in"
redirect_to :controller => 'admin', :action => 'login'
end
end
def set_locale
session[:locale] = params[:locale] if params[:locale]
I18n.locale = session[:locale] || I18n.default_locale
locale_path = "#{LOCALES_DIRECTORY}#{I18n.locale}.yml"
unless I18n.load_path.include? locale_path
I18n.load_path << locale_path
I18n.backend.send(:init_translations)
end
rescue Exception => err
logger.error err
flash.now[:notice] = "#{I18n.locale} translation not available"
I18n.load_path -= [locale_path]
I18n.locale = session[:locale] = I18n.default_locale
end
end
edit public/stylesheets/depot.css
.locale {
float:right;
padding-top: 0.2em
}
restart
get /store?locale=es
es translation not available
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
edit app/views/layouts/store.html.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Pragprog Books Online Store</title>
<%= stylesheet_link_tag "depot", :media => "all" %>
<%= javascript_include_tag :defaults %>
</head>
<body id="store">
<div id="banner">
<% form_tag '', :method => 'GET', :class => 'locale' do %>
<%= select_tag 'locale', options_for_select(LANGUAGES, I18n.locale),
:onchange => 'this.form.submit()' %>
<%= submit_tag 'submit' %>
<%= javascript_tag "$$('.locale input').each(Element.hide)" %>
<% end %>
<%= image_tag("logo.png") %>
<%= @page_title || I18n.t('layout.title') %>
</div>
<div id="columns">
<div id="side">
<% if @cart %>
<% hidden_div_if(@cart.items.empty?, :id => "cart") do %>
<%= render(:partial => "cart", :object => @cart) %>
<% end %>
<% end %>
<a href="http://www...."><%= I18n.t 'layout.side.home' %></a><br />
<a href="http://www..../faq"><%= I18n.t 'layout.side.questions' %></a><br />
<a href="http://www..../news"><%= I18n.t 'layout.side.news' %></a><br />
<a href="http://www..../contact"><%= I18n.t 'layout.side.contact' %></a><br />
<% if session[:user_id] %>
<br />
<%= link_to 'Orders', :controller => 'orders' %><br />
<%= link_to 'Products', :controller => 'products' %><br />
<%= link_to 'Users', :controller => 'users' %><br />
<br />
<%= link_to 'Logout', :controller => 'admin', :action => 'logout' %>
<% end %>
</div>
<div id="main">
<% if flash[:notice] -%>
<div id="notice"><%= flash[:notice] %></div>
<% end -%>
<%= yield :layout %>
</div>
</div>
</body>
</html>
cp -r /Users/rubys/git/awdwr/data/i18n/*.yml config/locales
get /store?locale=es
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
edit app/views/store/index.html.erb
<h1><%= I18n.t 'main.title' %></h1>
<% for product in @products -%>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%=h product.title %></h3>
<%= product.description %>
<div class="price-line">
<span class="price"><%= number_to_currency(product.price) %></span>
<% form_remote_tag :url => {:action => 'add_to_cart', :id => product} do %>
<%= submit_tag I18n.t('main.button.add') %>
<% end %>
</div>
</div>
<% end %>
get /store?locale=es
Su Catálogo de Pragmatic
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
edit app/views/store/_cart.html.erb
<div class="cart-title"><%= I18n.t 'layout.cart.title' %></div>
<table>
<%= render(:partial => "cart_item", :collection => cart.items) %>
<tr class="total-line">
<td colspan="2">Total</td>
<td class="total-cell"><%= number_to_currency(cart.total_price) %></td>
</tr>
</table>
<%= button_to I18n.t('layout.cart.button.checkout'), :action => 'checkout' %>
<%= button_to I18n.t('layout.cart.button.empty'), :action => :empty_cart %>
get /store/add_to_cart/2
You are being
redirected .
get http://127.0.0.1:3000/store
Su Catálogo de Pragmatic
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
edit app/views/store/checkout.html.erb
<div class="depot-form">
<%= error_messages_for 'order' %>
<% form_for :order, :url => { :action => :save_order } do |form| %>
<fieldset>
<legend><%= I18n.t 'checkout.legend' %></legend>
<div>
<%= form.label :name, I18n.t('checkout.name') + ":" %>
<%= form.text_field :name, :size => 40 %>
</div>
<div>
<%= form.label :address, I18n.t('checkout.address') + ":" %>
<%= form.text_area :address, :rows => 3, :cols => 40 %>
</div>
<div>
<%= form.label :email, I18n.t('checkout.email') + ":" %>
<%= form.text_field :email, :size => 40 %>
</div>
<div>
<%= form.label :pay_type, I18n.t('checkout.pay_type') + ":" %>
<%=
form.select :pay_type,
Order::PAYMENT_TYPES,
:prompt => I18n.t('checkout.pay_prompt')
%>
</div>
<%= submit_tag I18n.t('checkout.submit'), :class => "submit" %>
</fieldset>
<% end %>
</div>
edit app/controllers/store_controller.rb
class StoreController < ApplicationController
before_filter :find_cart, :except => :empty_cart
def index
@products = Product.find_products_for_sale
end
def add_to_cart
product = Product.find(params[:id])
@current_item = @cart.add_product(product)
respond_to do |format|
format.js if request.xhr?
format.html {redirect_to_index}
end
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
end
def checkout
if @cart.items.empty?
redirect_to_index("Your cart is empty")
else
@order = Order.new
end
end
def save_order
@order = Order.new(params[:order])
@order.add_line_items_from_cart(@cart)
if @order.save
session[:cart] = nil
redirect_to_index(I18n.t('flash.thanks'))
else
render :action => 'checkout'
end
end
def empty_cart
session[:cart] = nil
redirect_to_index
end
private
def redirect_to_index(msg = nil)
flash[:notice] = msg if msg
redirect_to :action => 'index'
end
def find_cart
@cart = (session[:cart] ||= Cart.new)
end
#...
protected
def authorize
end
end
get /store?locale=es
Su Catálogo de Pragmatic
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
get /store/add_to_cart/2
You are being
redirected .
get http://127.0.0.1:3000/store
Su Catálogo de Pragmatic
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
get /store/checkout
get /store/save_order
get /store/save_order
post /store/save_order
order[pay_type] => check
order[address] => 123 Main St., Anytown USA
order[email] => juser@hotmail.com
order[name] => Joe User
You are being
redirected .
get http://127.0.0.1:3000/store
Gracias por su pedido
Su Catálogo de Pragmatic
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
get /store?locale=en
Your Pragmatic Catalog
Pragmatic Project Automation
Pragmatic Project Automation shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
Pragmatic Unit Testing (C#)
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
Pragmatic Version Control
This book is a recipe-based approach to using Subversion that will
get you up and running quickly---and correctly. All projects need
version control: it's a foundational piece of any project's
infrastructure. Yet half of all project teams in the U.S. don't use
any version control at all. Many others don't use it well, and end
up experiencing time-consuming problems.
14.1 Tests Baked Right In
ls -p test
fixtures/
functional/
integration/
performance/
test_helper.rb
unit/
ls test/unit
line_item_test.rb
order_test.rb
product_test.rb
user_test.rb
ls test/functional
admin_controller_test.rb
info_controller_test.rb
line_items_controller_test.rb
orders_controller_test.rb
products_controller_test.rb
store_controller_test.rb
users_controller_test.rb
14.2 Unit Testing of Models
cat test/unit/product_test.rb
require 'test_helper'
class ProductTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
ruby -Itest test/unit/product_test.rb
Loaded suite test/unit/product_test
Started
E
Finished in 0.13622 seconds.
1) Error:
test_the_truth(ProductTest):
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: users: DELETE FROM "users" WHERE 1=1
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract_adapter.rb:188:in `log'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/sqlite_adapter.rb:132:in `execute'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/sqlite_adapter.rb:372:in `catch_schema_changes'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/sqlite_adapter.rb:132:in `execute'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/database_statements.rb:177:in `update_sql'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/sqlite_adapter.rb:136:in `update_sql'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/database_statements.rb:182:in `delete_sql'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/sqlite_adapter.rb:142:in `delete_sql'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/database_statements.rb:54:in `delete_without_query_dirty'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/query_cache.rb:18:in `delete'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/fixtures.rb:558:in `delete_existing_fixtures'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/fixtures.rb:519:in `create_fixtures'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/fixtures.rb:519:in `each'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/fixtures.rb:519:in `create_fixtures'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/database_statements.rb:66:in `transaction'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/fixtures.rb:518:in `create_fixtures'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract_adapter.rb:93:in `disable_referential_integrity'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/fixtures.rb:509:in `create_fixtures'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1398:in `silence'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/fixtures.rb:508:in `create_fixtures'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/fixtures.rb:964:in `load_fixtures'
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/fixtures.rb:930:in `setup_fixtures'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:178:in `send'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:178:in `evaluate_method'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:166:in `call'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:90:in `run'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:90:in `each'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:90:in `send'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:90:in `run'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:277:in `run_callbacks'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/testing/setup_and_teardown.rb:58:in `run'
1 tests, 0 assertions, 0 failures, 1 errors
rake db:test:prepare
(in /Users/rubys/git/awdwr/work/depot)
ruby -Itest test/unit/product_test.rb
Loaded suite test/unit/product_test
Started
.
Finished in 0.234952 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
rake test:units
(in /Users/rubys/git/awdwr/work/depot)
/opt/local/bin/ruby -Ilib:test "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/unit/line_item_test.rb" "test/unit/order_test.rb" "test/unit/product_test.rb" "test/unit/user_test.rb"
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Started
....
Finished in 0.189578 seconds.
4 tests, 4 assertions, 0 failures, 0 errors
edit test/unit/product_test.rb
require 'test_helper'
class ProductTest < ActiveSupport::TestCase
fixtures :products
# Replace this with your real tests.
test "the truth" do
assert true
end
test "invalid with empty attributes" do
product = Product.new
assert !product.valid?
assert product.errors.invalid?(:title)
assert product.errors.invalid?(:description)
assert product.errors.invalid?(:price)
assert product.errors.invalid?(:image_url)
end
test "positive price" do
product = Product.new(:title => "My Book Title",
:description => "yyy",
:image_url => "zzz.jpg")
product.price = -1
assert !product.valid?
assert_equal "should be at least 0.01", product.errors.on(:price)
product.price = 0
assert !product.valid?
assert_equal "should be at least 0.01", product.errors.on(:price)
product.price = 1
assert product.valid?
end
test "image url" do
ok = %w{ fred.gif fred.jpg fred.png FRED.JPG FRED.Jpg
http://a.b.c/x/y/z/fred.gif }
bad = %w{ fred.doc fred.gif/more fred.gif.more }
ok.each do |name|
product = Product.new(:title => "My Book Title",
:description => "yyy",
:price => 1,
:image_url => name)
assert product.valid?, product.errors.full_messages
end
bad.each do |name|
product = Product.new(:title => "My Book Title",
:description => "yyy",
:price => 1,
:image_url => name)
assert !product.valid?, "saving #{name}"
end
end
test "unique title" do
product = Product.new(:title => products(:ruby_book).title,
:description => "yyy",
:price => 1,
:image_url => "fred.gif")
assert !product.save
assert_equal "has already been taken", product.errors.on(:title)
end
test "unique title1" do
product = Product.new(:title => products(:ruby_book).title,
:description => "yyy",
:price => 1,
:image_url => "fred.gif")
assert !product.save
assert_equal I18n.translate('activerecord.errors.messages.taken'),
product.errors.on(:title)
end
end
edit test/fixtures/products.yml
ruby_book:
title: Programming Ruby
description: Dummy description
price: 1234
image_url: ruby.png
rails_book:
title: Agile Web Development with Rails
description: Dummy description
price: 2345
image_url: rails.png
rake test:units
(in /Users/rubys/git/awdwr/work/depot)
/opt/local/bin/ruby -Ilib:test "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/unit/line_item_test.rb" "test/unit/order_test.rb" "test/unit/product_test.rb" "test/unit/user_test.rb"
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Started
.........
Finished in 0.375895 seconds.
9 tests, 27 assertions, 0 failures, 0 errors
edit test/unit/cart_test.rb
require 'test_helper'
class CartTest < ActiveSupport::TestCase
fixtures :products
def test_add_unique_products
cart = Cart.new
rails_book = products(:rails_book)
ruby_book = products(:ruby_book)
cart.add_product rails_book
cart.add_product ruby_book
assert_equal 2, cart.items.size
assert_equal rails_book.price + ruby_book.price, cart.total_price
end
def test_add_duplicate_product
cart = Cart.new
rails_book = products(:rails_book)
cart.add_product rails_book
cart.add_product rails_book
assert_equal 2*rails_book.price, cart.total_price
assert_equal 1, cart.items.size
assert_equal 2, cart.items[0].quantity
end
end
ruby -I test test/unit/cart_test.rb
Loaded suite test/unit/cart_test
Started
..
Finished in 0.257254 seconds.
2 tests, 5 assertions, 0 failures, 0 errors
edit test/unit/cart_test1.rb
require 'test_helper'
class CartTest < ActiveSupport::TestCase
fixtures :products
def setup
@cart = Cart.new
@rails = products(:rails_book)
@ruby = products(:ruby_book)
end
def test_add_unique_products
@cart.add_product @rails
@cart.add_product @ruby
assert_equal 2, @cart.items.size
assert_equal @rails.price + @ruby.price, @cart.total_price
end
def test_add_duplicate_product
@cart.add_product @rails
@cart.add_product @rails
assert_equal 2*@rails.price, @cart.total_price
assert_equal 1, @cart.items.size
assert_equal 2, @cart.items[0].quantity
end
end
ruby -I test test/unit/cart_test1.rb
Loaded suite test/unit/cart_test1
Started
..
Finished in 0.2602 seconds.
2 tests, 5 assertions, 0 failures, 0 errors
14.3 Functional Testing of Controllers
edit app/controllers/application.rb
class ApplicationController < ActionController::Base
layout "store"
before_filter :authorize, :except => :login
#...
protected
def authorize
unless User.find_by_id(session[:user_id])
flash[:notice] = "Please log in"
redirect_to :controller => 'admin', :action => 'login'
end
end
def set_locale
session[:locale] = params[:locale] if params[:locale]
I18n.locale = session[:locale] || I18n.default_locale
locale_path = "#{LOCALES_DIRECTORY}#{I18n.locale}.yml"
unless I18n.load_path.include? locale_path
I18n.load_path << locale_path
I18n.backend.send(:init_translations)
end
rescue Exception => err
logger.error err
flash.now[:notice] = "#{I18n.locale} translation not available"
I18n.load_path -= [locale_path]
I18n.locale = session[:locale] = I18n.default_locale
end
end
edit test/functional/admin_controller_test.rb
require 'test_helper'
class AdminControllerTest < ActionController::TestCase
fixtures :users
# Replace this with your real tests.
test "the truth" do
assert true
end
if false
test "index" do
get :index
assert_response :success
end
end
test "index without user" do
get :index
assert_redirected_to :action => "login"
assert_equal "Please log in", flash[:notice]
end
test "index with user" do
get :index, {}, { :user_id => users(:dave).id }
assert_response :success
assert_template "index"
end
test "login" do
dave = users(:dave)
post :login, :name => dave.name, :password => 'secret'
assert_redirected_to :action => "index"
assert_equal dave.id, session[:user_id]
end
test "bad password" do
dave = users(:dave)
post :login, :name => dave.name, :password => 'wrong'
assert_template "login"
end
end
edit test/fixtures/users.yml
<% SALT = "NaCl" unless defined?(SALT) %>
dave:
name: dave
salt: <%= SALT %>
hashed_password: <%= User.encrypted_password('secret', SALT) %>
ruby -I test test/functional/admin_controller_test.rb
Loaded suite test/functional/admin_controller_test
Started
.....
Finished in 0.411941 seconds.
5 tests, 8 assertions, 0 failures, 0 errors
14.4 Integration Testing of Applications
ruby script/generate integration_test user_stories
exists test/integration/
create test/integration/user_stories_test.rb
edit test/integration/user_stories_test.rb
require 'test_helper'
class UserStoriesTest < ActionController::IntegrationTest
fixtures :products
# A user goes to the index page. They select a product, adding it to their
# cart, and check out, filling in their details on the checkout form. When
# they submit, an order is created containing their information, along with a
# single line item corresponding to the product they added to their cart.
test "buying a product" do
LineItem.delete_all
Order.delete_all
ruby_book = products(:ruby_book)
get "/store/index"
assert_response :success
assert_template "index"
xml_http_request :put, "/store/add_to_cart", :id => ruby_book.id
assert_response :success
cart = session[:cart]
assert_equal 1, cart.items.size
assert_equal ruby_book, cart.items[0].product
post "/store/checkout"
assert_response :success
assert_template "checkout"
post_via_redirect "/store/save_order",
:order => { :name => "Dave Thomas",
:address => "123 The Street",
:email => "dave@pragprog.com",
:pay_type => "check" }
assert_response :success
assert_template "index"
assert_equal 0, session[:cart].items.size
orders = Order.find(:all)
assert_equal 1, orders.size
order = orders[0]
assert_equal "Dave Thomas", order.name
assert_equal "123 The Street", order.address
assert_equal "dave@pragprog.com", order.email
assert_equal "check", order.pay_type
assert_equal 1, order.line_items.size
line_item = order.line_items[0]
assert_equal ruby_book, line_item.product
end
end
ruby -I test test/integration/user_stories_test.rb
Loaded suite test/integration/user_stories_test
Started
.
Finished in 0.504548 seconds.
1 tests, 17 assertions, 0 failures, 0 errors
edit test/integration/dsl_user_stories_test.rb
require 'test_helper'
class DslUserStoriesTest < ActionController::IntegrationTest
fixtures :products
DAVES_DETAILS = {
:name => "Dave Thomas",
:address => "123 The Street",
:email => "dave@pragprog.com",
:pay_type => "check"
}
MIKES_DETAILS = {
:name => "Mike Clark",
:address => "345 The Avenue",
:email => "mike@pragmaticstudio.com",
:pay_type => "cc"
}
def setup
LineItem.delete_all
Order.delete_all
@ruby_book = products(:ruby_book)
@rails_book = products(:rails_book)
end
# A user goes to the store index page. They select a product,
# adding it to their cart. They then check out, filling in
# their details on the checkout form. When they submit,
# an order is created in the database containing
# their information, along with a single line item
# corresponding to the product they added to their cart.
def test_buying_a_product
dave = regular_user
dave.get "/store/index"
dave.is_viewing "index"
dave.buys_a @ruby_book
dave.has_a_cart_containing @ruby_book
dave.checks_out DAVES_DETAILS
dave.is_viewing "index"
check_for_order DAVES_DETAILS, @ruby_book
end
def test_two_people_buying
dave = regular_user
mike = regular_user
dave.buys_a @ruby_book
mike.buys_a @rails_book
dave.has_a_cart_containing @ruby_book
dave.checks_out DAVES_DETAILS
mike.has_a_cart_containing @rails_book
check_for_order DAVES_DETAILS, @ruby_book
mike.checks_out MIKES_DETAILS
check_for_order MIKES_DETAILS, @rails_book
end
def regular_user
open_session do |user|
def user.is_viewing(page)
assert_response :success
assert_template page
end
def user.buys_a(product)
xml_http_request :put, "/store/add_to_cart", :id => product.id
assert_response :success
end
def user.has_a_cart_containing(*products)
cart = session[:cart]
assert_equal products.size, cart.items.size
for item in cart.items
assert products.include?(item.product)
end
end
def user.checks_out(details)
post "/store/checkout"
assert_response :success
assert_template "checkout"
post_via_redirect "/store/save_order",
:order => { :name => details[:name],
:address => details[:address],
:email => details[:email],
:pay_type => details[:pay_type]
}
assert_response :success
assert_template "index"
assert_equal 0, session[:cart].items.size
end
end
end
def check_for_order(details, *products)
order = Order.find_by_name(details[:name])
assert_not_nil order
assert_equal details[:name], order.name
assert_equal details[:address], order.address
assert_equal details[:email], order.email
assert_equal details[:pay_type], order.pay_type
assert_equal products.size, order.line_items.size
for line_item in order.line_items
assert products.include?(line_item.product)
end
end
end
ruby -I test test/integration/dsl_user_stories_test.rb
Loaded suite test/integration/dsl_user_stories_test
Started
..
Finished in 0.965691 seconds.
2 tests, 49 assertions, 0 failures, 0 errors
14.5 Performance Testing
mkdir test/fixtures/performance/
edit test/fixtures/performance/products.yml
<% 1.upto(1000) do |i| %>
product_<%= i %>:
id: <%= i %>
title: Product Number <%= i %>
description: My description
image_url: product.gif
price: 1234
<% end %>
edit test/performance/order_speed_test.rb
require 'test_helper'
require 'store_controller'
class OrderSpeedTest < ActionController::TestCase
tests StoreController
DAVES_DETAILS = {
:name => "Dave Thomas",
:address => "123 The Street",
:email => "dave@pragprog.com",
:pay_type => "check"
}
self.fixture_path = File.join(File.dirname(__FILE__), "../fixtures/performance")
fixtures :products
def test_100_orders
Order.delete_all
LineItem.delete_all
@controller.logger.silence do
elapsed_time = Benchmark.realtime do
100.downto(1) do |prd_id|
cart = Cart.new
cart.add_product(Product.find(prd_id))
post :save_order,
{ :order => DAVES_DETAILS },
{ :cart => cart }
assert_redirected_to :action => :index
end
end
assert_equal 100, Order.count
assert elapsed_time < 3.00
end
end
end
ruby -I test test/performance/order_speed_test.rb
Loaded suite test/performance/order_speed_test
Started
F
Finished in 9.661794 seconds.
1) Failure:
test_100_orders(OrderSpeedTest)
[test/performance/order_speed_test.rb:39:in `test_100_orders'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/buffered_logger.rb:25:in `silence'
test/performance/order_speed_test.rb:26:in `test_100_orders'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/testing/setup_and_teardown.rb:60:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/testing/setup_and_teardown.rb:60:in `run']:
<false> is not true.
1 tests, 102 assertions, 1 failures, 0 errors
edit app/models/user.rb
require 'digest/sha1'
class User < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
attr_accessor :password_confirmation
validates_confirmation_of :password
validate :password_non_blank
def self.authenticate(name, password)
user = self.find_by_name(name)
if user
expected_password = encrypted_password(password, user.salt)
if user.hashed_password != expected_password
user = nil
end
end
user
end
# 'password' is a virtual attribute
def password
@password
end
def password=(pwd)
@password = pwd
return if pwd.blank?
create_new_salt
self.hashed_password = User.encrypted_password(self.password, self.salt)
end
def after_destroy
if User.count.zero?
raise "Can't delete last user"
end
end
private
def password_non_blank
errors.add(:password, "Missing password") if hashed_password.blank?
end
def create_new_salt
self.salt = self.object_id.to_s + rand.to_s
end
def self.encrypted_password(password, salt)
100000.times { Math.sin(1)}
string_to_hash = password + "wibble" + salt
Digest::SHA1.hexdigest(string_to_hash)
end
end
ruby script/performance/benchmarker "User.encrypted_password(\"secret\", \"salt\")"
user system total real
#1 0.400000 0.110000 0.510000 ( 0.507007)
ruby script/performance/profiler "User.encrypted_password(\"secret\", \"salt\")"
Loading Rails...
Using the standard Ruby profiler.
% cumulative self self total
time seconds seconds calls ms/call ms/call name
73.08 16.78 16.78 1 16780.00 22380.00 Integer#times
24.39 22.38 5.60 100000 0.06 0.06 Math.sin
0.70 22.54 0.16 4 40.00 62.50 Array#select
0.48 22.65 0.11 5 22.00 36.00 Array#map
0.39 22.74 0.09 857 0.11 0.11 Hash#key?
0.30 22.81 0.07 859 0.08 0.08 String#to_s
0.13 22.84 0.03 40 0.75 1.25 Array#each
0.09 22.86 0.02 8 2.50 2.50 ActiveSupport::Dependencies.qualified_const_defined?
0.09 22.88 0.02 9 2.22 2.22 ActiveSupport::CoreExtensions::Array::ExtractOptions.extract_options!
0.04 22.89 0.01 11 0.91 0.91 String#gsub
0.04 22.90 0.01 9 1.11 1.11 Module#blank_slate_method_added
0.04 22.91 0.01 1 10.00 320.00 Kernel.load_without_new_constant_marking
0.04 22.92 0.01 18 0.56 0.56 Kernel.is_a?
0.04 22.93 0.01 4 2.50 2.50 ActiveSupport::Callbacks::Callback#initialize
0.04 22.94 0.01 3 3.33 3.33 File#file?
0.04 22.95 0.01 7 1.43 1.43 Symbol#===
0.04 22.96 0.01 2 5.00 405.00 ActiveSupport::Dependencies.new_constants_in
0.00 22.96 0.00 6 0.00 0.00 ActiveSupport::Dependencies.constant_watch_stack
0.00 22.96 0.00 21 0.00 0.00 Hash#[]
0.00 22.96 0.00 4 0.00 7.50 ActiveSupport::Callbacks::CallbackChain#build
0.00 22.96 0.00 1 0.00 0.00 Digest::Base#finish
0.00 22.96 0.00 2 0.00 0.00 ActiveSupport::Dependencies.load_paths
0.00 22.96 0.00 9 0.00 0.00 ActiveSupport::Dependencies.log_activity
0.00 22.96 0.00 1 0.00 22380.00 User#encrypted_password
0.00 22.96 0.00 24 0.00 0.00 Module#constants
0.00 22.96 0.00 2 0.00 0.00 Kernel.equal?
0.00 22.96 0.00 4 0.00 0.00 Kernel.block_given?
0.00 22.96 0.00 12 0.00 0.00 String#empty?
0.00 22.96 0.00 1 0.00 0.00 Array#compact
0.00 22.96 0.00 1 0.00 540.00 ActiveSupport::Dependencies.load_file
0.00 22.96 0.00 1 0.00 0.00 TrueClass#duplicable?
0.00 22.96 0.00 2 0.00 0.00 Kernel.respond_to?
0.00 22.96 0.00 2 0.00 0.00 Kernel.hash
0.00 22.96 0.00 1 0.00 0.00 Digest::Class#digest
0.00 22.96 0.00 2 0.00 0.00 String#size
0.00 22.96 0.00 5 0.00 0.00 Array#initialize
0.00 22.96 0.00 10 0.00 0.00 ActiveSupport::Dependencies.uninherited_const_defined?
0.00 22.96 0.00 2 0.00 0.00 Class#inherited
0.00 22.96 0.00 5 0.00 0.00 Array#pop
0.00 22.96 0.00 12 0.00 0.00 String#split
0.00 22.96 0.00 1 0.00 0.00 Digest::Base#update
0.00 22.96 0.00 2 0.00 0.00 Kernel.dup