The Depot Application
Table of Contents
25.1 Sending E-mail
26 Active Resources
Restart the server.
ruby -rubygems /home/rubys/git/rails/railties/bin/rails depot_client
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 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_controller.rb
create app/helpers/application_helper.rb
create config/database.yml
create config/routes.rb
create config/locales/en.yml
create db/seeds.rb
create config/initializers/backtrace_silencers.rb
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/new_rails_defaults.rb
create config/initializers/session_store.rb
create config/initializers/cookie_verification_secret.rb
create config/environment.rb
create config/boot.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/runner
create script/server
create script/plugin
create script/performance/benchmarker
create script/performance/profiler
create test/test_helper.rb
create test/performance/browsing_test.rb
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 app/models/product.rb
class Product < ActiveResource::Base
self.site = 'http://dave:secret@localhost:3000/'
end
echo "Product.find(2).title" | IRBRC=tmp/irbrc ruby script/console
>> Product.find(2).title
ActiveResource::Redirection: Failed with 302 Found => http://localhost:3000/admin/login
from /home/rubys/git/awdwr/work-235/depot_client/vendor/rails/activeresource/lib/active_resource/connection.rb:184:in `handle_response'
from /home/rubys/git/awdwr/work-235/depot_client/vendor/rails/activeresource/lib/active_resource/connection.rb:173:in `request'
from /home/rubys/git/awdwr/work-235/depot_client/vendor/rails/activeresource/lib/active_resource/connection.rb:138:in `get'
from /home/rubys/git/awdwr/work-235/depot_client/vendor/rails/activeresource/lib/active_resource/base.rb:658:in `find_single'
from /home/rubys/git/awdwr/work-235/depot_client/vendor/rails/activeresource/lib/active_resource/base.rb:586:in `find'
from (irb):1
>>
edit app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
layout "store"
before_filter :authorize, :except => :login
#...
protected
def authorize
unless User.find_by_id(session[:user_id])
if session[:user_id] != :logged_out
authenticate_or_request_with_http_basic('Depot') do |username, password|
user = User.authenticate(username, password)
session[:user_id] = user.id if user
end
else
flash[:notice] = "Please log in"
redirect_to :controller => 'admin', :action => 'login'
end
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 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] = :logged_out
flash[:notice] = "Logged out"
redirect_to(:action => "login")
end
def index
@total_orders = Order.count
end
end
edit app/controllers/line_items_controller.rb
def create
params[:line_item][:order_id] ||= params[:order_id]
@line_item = LineItem.new(params[:line_item])
respond_to do |format|
if @line_item.save
format.html { redirect_to(@line_item, :notice => 'LineItem was successfully created.') }
format.xml { render :xml => @line_item, :status => :created,
:location => @line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => @line_item.errors,
:status => :unprocessable_entity }
end
end
end
edit config/routes.rb
ActionController::Routing::Routes.draw do |map|
map.resources :users
map.resources :line_items
map.resources :orders, :has_many => :line_items
map.resources :products
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
Restart the server.
echo "Product.find(2).title" | IRBRC=tmp/irbrc ruby script/console
>> Product.find(2).title
=> "Pragmatic Project Automation"
>>
echo "p = Product.find(2)\\nputs p.price\\np.price-=5\\np.save" | IRBRC=tmp/irbrc ruby script/console
>> p = Product.find(2)
=> #<Product:0xb753674c @prefix_options={}, @attributes={"price"=>#<BigDecimal:b753a608,'0.2995E2',8(8)>, "created_at"=>Mon Mar 01 14:10:49 UTC 2010, "image_url"=>"/images/auto.jpg", "title"=>"Pragmatic Project Automation", "updated_at"=>Mon Mar 01 14:10:49 UTC 2010, "id"=>2, "description"=>"<p>\n <em>Pragmatic Project Automation</em> shows you how to improve the \n consistency and repeatability of your project's procedures using \n automation to reduce risk and errors.\n </p>\n <p>\n Simply put, we're going to put this thing called a computer to work \n for you doing the mundane (but important) project stuff. That means \n you'll have more time and energy to do the really \n exciting---and difficult---stuff, like writing quality code.\n </p>"}>
>> puts p.price
29.95
=> nil
>> p.price-=5
=> #<BigDecimal:b74d3354,'0.2495E2',8(16)>
>> p.save
=> true
>>
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/models/order.rb
class Order < ActiveResource::Base
self.site = 'http://dave:secret@localhost:3000/'
end
echo "Order.find(1).name\\nOrder.find(1).line_items\\n" | IRBRC=tmp/irbrc ruby script/console
>> Order.find(1).name
=> "Dave Thomas"
>> Order.find(1).line_items
NoMethodError: undefined method `line_items' for #<Order:0xb7465714>
from /home/rubys/git/awdwr/work-235/depot_client/vendor/rails/activeresource/lib/active_resource/base.rb:1153:in `method_missing'
from (irb):2
>>
?> >>
edit app/models/line_item.rb
class LineItem < ActiveResource::Base
self.site = 'http://dave:secret@localhost:3000/orders/:order_id'
end
get /admin/logout
HTTP Basic: Access denied.
get /admin/login
Pragmatic Bookshelf
post /admin/login
name => dave
password => secret
You are being
redirected .
get http://localhost:3000/admin
Pragmatic Bookshelf
Welcome
It's Mon Mar 01 09:16:42 -0500 2010
We have 2 orders.
get /orders/1/line_items.xml
<?xml version="1.0" encoding="UTF-8"?>
<line-items type="array">
<line-item>
<created-at type="datetime">2010-03-01T14:11:44Z</created-at>
<id type="integer">1</id>
<order-id type="integer">1</order-id>
<product-id type="integer">3</product-id>
<quantity type="integer">1</quantity>
<total-price type="decimal">28.5</total-price>
<updated-at type="datetime">2010-03-01T14:11:44Z</updated-at>
</line-item>
<line-item>
<created-at type="datetime">2010-03-01T14:12:44Z</created-at>
<id type="integer">2</id>
<order-id type="integer">2</order-id>
<product-id type="integer">2</product-id>
<quantity type="integer">2</quantity>
<total-price type="decimal">59.9</total-price>
<updated-at type="datetime">2010-03-01T14:12:44Z</updated-at>
</line-item>
</line-items>
echo "LineItem.find(:all, :params => {:order_id=>1})" | IRBRC=tmp/irbrc ruby script/console
>> LineItem.find(:all, :params => {:order_id=>1})
=> [#<LineItem:0xb746b7e0 @prefix_options={:order_id=>1}, @attributes={"created_at"=>Mon Mar 01 14:11:44 UTC 2010, "product_id"=>3, "quantity"=>1, "updated_at"=>Mon Mar 01 14:11:44 UTC 2010, "total_price"=>#<BigDecimal:b746f458,'0.285E2',8(8)>, "id"=>1}>, #<LineItem:0xb746b77c @prefix_options={:order_id=>1}, @attributes={"created_at"=>Mon Mar 01 14:12:44 UTC 2010, "product_id"=>2, "quantity"=>2, "updated_at"=>Mon Mar 01 14:12:44 UTC 2010, "total_price"=>#<BigDecimal:b746bb50,'0.599E2',8(8)>, "id"=>2}>]
>>
echo "li = LineItem.find(:all, :params => {:order_id=>1}).first\\nputs li.total_price\\nli.total_price*=0.8\\nli.save\\nli2 = LineItem.new(:order_id=>1, :product_id=>2, :quantity=>1, :total_price=>0.0)\\nli2.save" | IRBRC=tmp/irbrc ruby script/console
>> li = LineItem.find(:all, :params => {:order_id=>1}).first
=> #<LineItem:0xb7483354 @prefix_options={:order_id=>1}, @attributes={"created_at"=>Mon Mar 01 14:11:44 UTC 2010, "product_id"=>3, "quantity"=>1, "updated_at"=>Mon Mar 01 14:11:44 UTC 2010, "total_price"=>#<BigDecimal:b748607c,'0.285E2',8(8)>, "id"=>1}>
>> puts li.total_price
28.5
=> nil
>> li.total_price*=0.8
=> 22.8
>> li.save
=> true
>> li2 = LineItem.new(:order_id=>1, :product_id=>2, :quantity=>1, :total_price=>0.0)
=> #<LineItem:0xb741375c @prefix_options={:order_id=>1}, @attributes={"product_id"=>2, "quantity"=>1, "total_price"=>0.0}>
>> li2.save
=> true
>>
Table of Contents
25.1 Sending E-mail