Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

adding episode 220

  • Loading branch information...
commit 0e3674060995d820baeccbc677f3dd3a15e29b59 1 parent f355558
@ryanb authored
Showing with 9,640 additions and 0 deletions.
  1. +8 −0 episode-220/README
  2. +4 −0 episode-220/store/.gitignore
  3. +32 −0 episode-220/store/Gemfile
  4. +281 −0 episode-220/store/README
  5. +7 −0 episode-220/store/Rakefile
  6. +4 −0 episode-220/store/app/controllers/application_controller.rb
  7. +5 −0 episode-220/store/app/controllers/carts_controller.rb
  8. +44 −0 episode-220/store/app/controllers/categories_controller.rb
  9. +8 −0 episode-220/store/app/controllers/line_items_controller.rb
  10. +23 −0 episode-220/store/app/controllers/orders_controller.rb
  11. +44 −0 episode-220/store/app/controllers/products_controller.rb
  12. +2 −0  episode-220/store/app/helpers/application_helper.rb
  13. +2 −0  episode-220/store/app/helpers/carts_helper.rb
  14. +2 −0  episode-220/store/app/helpers/categories_helper.rb
  15. +23 −0 episode-220/store/app/helpers/error_messages_helper.rb
  16. +22 −0 episode-220/store/app/helpers/layout_helper.rb
  17. +2 −0  episode-220/store/app/helpers/line_items_helper.rb
  18. +2 −0  episode-220/store/app/helpers/orders_helper.rb
  19. +2 −0  episode-220/store/app/helpers/products_helper.rb
  20. +9 −0 episode-220/store/app/models/cart.rb
  21. +3 −0  episode-220/store/app/models/category.rb
  22. +8 −0 episode-220/store/app/models/line_item.rb
  23. +55 −0 episode-220/store/app/models/order.rb
  24. +16 −0 episode-220/store/app/models/order_transaction.rb
  25. +3 −0  episode-220/store/app/models/product.rb
  26. +4 −0 episode-220/store/app/views/carts/purchase.html.erb
  27. +28 −0 episode-220/store/app/views/carts/show.html.erb
  28. +7 −0 episode-220/store/app/views/categories/_form.html.erb
  29. +8 −0 episode-220/store/app/views/categories/edit.html.erb
  30. +13 −0 episode-220/store/app/views/categories/index.html.erb
  31. +5 −0 episode-220/store/app/views/categories/new.html.erb
  32. +13 −0 episode-220/store/app/views/categories/show.html.erb
  33. +22 −0 episode-220/store/app/views/layouts/application.html.erb
  34. +1 −0  episode-220/store/app/views/orders/failure.html.erb
  35. +32 −0 episode-220/store/app/views/orders/new.html.erb
  36. +29 −0 episode-220/store/app/views/orders/show.html.erb
  37. +1 −0  episode-220/store/app/views/orders/success.html.erb
  38. +20 −0 episode-220/store/app/views/products/_form.html.erb
  39. +8 −0 episode-220/store/app/views/products/edit.html.erb
  40. +17 −0 episode-220/store/app/views/products/index.html.erb
  41. +5 −0 episode-220/store/app/views/products/new.html.erb
  42. +24 −0 episode-220/store/app/views/products/show.html.erb
  43. +4 −0 episode-220/store/config.ru
  44. +47 −0 episode-220/store/config/application.rb
  45. +13 −0 episode-220/store/config/boot.rb
  46. +22 −0 episode-220/store/config/database.yml
  47. +5 −0 episode-220/store/config/environment.rb
  48. +19 −0 episode-220/store/config/environments/development.rb
  49. +46 −0 episode-220/store/config/environments/production.rb
  50. +32 −0 episode-220/store/config/environments/test.rb
  51. +7 −0 episode-220/store/config/initializers/backtrace_silencers.rb
  52. +10 −0 episode-220/store/config/initializers/inflections.rb
  53. +5 −0 episode-220/store/config/initializers/mime_types.rb
  54. +7 −0 episode-220/store/config/initializers/secret_token.rb
  55. +8 −0 episode-220/store/config/initializers/session_store.rb
  56. +5 −0 episode-220/store/config/locales/en.yml
  57. +8 −0 episode-220/store/config/routes.rb
  58. +12 −0 episode-220/store/db/migrate/20080621194238_create_categories.rb
  59. +15 −0 episode-220/store/db/migrate/20080621194423_create_products.rb
  60. +12 −0 episode-220/store/db/migrate/20081221210944_create_carts.rb
  61. +15 −0 episode-220/store/db/migrate/20081221211031_create_line_items.rb
  62. +17 −0 episode-220/store/db/migrate/20090119051232_create_orders.rb
  63. +19 −0 episode-220/store/db/migrate/20090119062501_create_order_transactions.rb
  64. +67 −0 episode-220/store/db/schema.rb
  65. +7 −0 episode-220/store/db/seeds.rb
  66. +2 −0  episode-220/store/doc/README_FOR_APP
  67. 0  episode-220/store/lib/tasks/.gitkeep
  68. +26 −0 episode-220/store/public/404.html
  69. +26 −0 episode-220/store/public/422.html
  70. +26 −0 episode-220/store/public/500.html
  71. 0  episode-220/store/public/favicon.ico
  72. BIN  episode-220/store/public/images/rails.png
  73. +2 −0  episode-220/store/public/javascripts/application.js
  74. +965 −0 episode-220/store/public/javascripts/controls.js
  75. +974 −0 episode-220/store/public/javascripts/dragdrop.js
  76. +1,123 −0 episode-220/store/public/javascripts/effects.js
  77. +4,874 −0 episode-220/store/public/javascripts/prototype.js
  78. +118 −0 episode-220/store/public/javascripts/rails.js
  79. +5 −0 episode-220/store/public/robots.txt
  80. 0  episode-220/store/public/stylesheets/.gitkeep
  81. +149 −0 episode-220/store/public/stylesheets/application.css
  82. +6 −0 episode-220/store/script/rails
  83. +11 −0 episode-220/store/test/fixtures/products.yml
  84. +54 −0 episode-220/store/test/functional/products_controller_test.rb
  85. +9 −0 episode-220/store/test/performance/browsing_test.rb
  86. +13 −0 episode-220/store/test/test_helper.rb
  87. +7 −0 episode-220/store/test/unit/product_test.rb
  88. 0  episode-220/store/vendor/plugins/.gitkeep
View
8 episode-220/README
@@ -0,0 +1,8 @@
+Railscasts Episode #220: PDFKit
+
+http://railscasts.com/episodes/220
+
+Commands
+
+ bundle install
+ rake middleware
View
4 episode-220/store/.gitignore
@@ -0,0 +1,4 @@
+.bundle
+db/*.sqlite3
+log/*.log
+tmp/**/*
View
32 episode-220/store/Gemfile
@@ -0,0 +1,32 @@
+source 'http://rubygems.org'
+
+gem 'rails', '3.0.0.beta4'
+
+# Bundle edge Rails instead:
+# gem 'rails', :git => 'git://github.com/rails/rails.git'
+
+gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'
+
+# Use unicorn as the web server
+# gem 'unicorn'
+
+# Deploy with Capistrano
+# gem 'capistrano'
+
+# To use debugger
+# gem 'ruby-debug'
+
+# Bundle the extra gems:
+# gem 'bj'
+# gem 'nokogiri', '1.4.1'
+# gem 'sqlite3-ruby', :require => 'sqlite3'
+# gem 'aws-s3', :require => 'aws/s3'
+
+# Bundle gems for certain environments:
+# gem 'rspec', :group => :test
+# group :test do
+# gem 'webrat'
+# end
+
+gem "nifty-generators"
+gem "pdfkit"
View
281 episode-220/store/README
@@ -0,0 +1,281 @@
+== Welcome to Rails
+
+Rails is a web-application framework that includes everything needed to create
+database-backed web applications according to the Model-View-Control pattern.
+
+This pattern splits the view (also called the presentation) into "dumb"
+templates that are primarily responsible for inserting pre-built data in between
+HTML tags. The model contains the "smart" domain objects (such as Account,
+Product, Person, Post) that holds all the business logic and knows how to
+persist themselves to a database. The controller handles the incoming requests
+(such as Save New Account, Update Product, Show Post) by manipulating the model
+and directing data to the view.
+
+In Rails, the model is handled by what's called an object-relational mapping
+layer entitled Active Record. This layer allows you to present the data from
+database rows as objects and embellish these data objects with business logic
+methods. You can read more about Active Record in
+link:files/vendor/rails/activerecord/README.html.
+
+The controller and view are handled by the Action Pack, which handles both
+layers by its two parts: Action View and Action Controller. These two layers
+are bundled in a single package due to their heavy interdependence. This is
+unlike the relationship between the Active Record and Action Pack that is much
+more separate. Each of these packages can be used independently outside of
+Rails. You can read more about Action Pack in
+link:files/vendor/rails/actionpack/README.html.
+
+
+== Getting Started
+
+1. At the command prompt, create a new Rails application:
+ <tt>rails myapp</tt> (where <tt>myapp</tt> is the application name)
+
+2. Change directory to <tt>myapp</tt> and start the web server:
+ <tt>cd myapp; rails server</tt> (run with --help for options)
+
+3. Go to http://localhost:3000/ and you'll see:
+ "Welcome aboard: You're riding the Rails!"
+
+4. Follow the guidelines to start developing your application. You can find
+the following resources handy:
+
+* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
+* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
+
+
+== Web Servers
+
+By default, Rails will try to use Mongrel if it's installed when started with
+<tt>rails server</tt>, otherwise Rails will use WEBrick, the web server that
+ships with Ruby.
+
+Mongrel is a Ruby-based web server with a C component (which requires
+compilation) that is suitable for development. If you have Ruby Gems installed,
+getting up and running with mongrel is as easy as:
+ <tt>sudo gem install mongrel</tt>.
+
+You can find more info at: http://mongrel.rubyforge.org
+
+You can alternatively run Rails applications with other Ruby web servers, e.g.,
+{Thin}[http://code.macournoyer.com/thin/], {Ebb}[http://ebb.rubyforge.org/], and
+Apache with {mod_rails}[http://www.modrails.com/]. However, <tt>rails server</tt>
+doesn't search for or start them.
+
+For production use, often a web/proxy server, e.g., {Apache}[http://apache.org],
+{Nginx}[http://nginx.net/], {LiteSpeed}[http://litespeedtech.com/],
+{Lighttpd}[http://www.lighttpd.net/], or {IIS}[http://www.iis.net/], is deployed
+as the front end server with the chosen Ruby web server running in the back end
+and receiving the proxied requests via one of several protocols (HTTP, CGI, FCGI).
+
+
+== Debugging Rails
+
+Sometimes your application goes wrong. Fortunately there are a lot of tools that
+will help you debug it and get it back on the rails.
+
+First area to check is the application log files. Have "tail -f" commands
+running on the server.log and development.log. Rails will automatically display
+debugging and runtime information to these files. Debugging info will also be
+shown in the browser on requests from 127.0.0.1.
+
+You can also log your own messages directly into the log file from your code
+using the Ruby logger class from inside your controllers. Example:
+
+ class WeblogController < ActionController::Base
+ def destroy
+ @weblog = Weblog.find(params[:id])
+ @weblog.destroy
+ logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
+ end
+ end
+
+The result will be a message in your log file along the lines of:
+
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
+
+More information on how to use the logger is at http://www.ruby-doc.org/core/
+
+Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
+several books available online as well:
+
+* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
+* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
+
+These two books will bring you up to speed on the Ruby language and also on
+programming in general.
+
+
+== Debugger
+
+Debugger support is available through the debugger command when you start your
+Mongrel or WEBrick server with --debugger. This means that you can break out of
+execution at any point in the code, investigate and change the model, and then,
+resume execution! You need to install ruby-debug to run the server in debugging
+mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find(:all)
+ debugger
+ end
+ end
+
+So the controller will accept the action, run the first line, then present you
+with a IRB prompt in the server window. Here you can do things like:
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8
+ @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
+ #<Post:0x14a6620
+ @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
+ >> @posts.first.title = "hello from a debugger"
+ => "hello from a debugger"
+
+...and even better, you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+Finally, when you're ready to resume execution, you can enter "cont".
+
+
+== Console
+
+The console is a Ruby shell, which allows you to interact with your
+application's domain model. Here you'll have all parts of the application
+configured, just like it is when the application is running. You can inspect
+domain models, change values, and save to the database. Starting the script
+without arguments will launch it in the development environment.
+
+To start the console, run <tt>rails console</tt> from the application
+directory.
+
+Options:
+
+* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
+ made to the database.
+* Passing an environment name as an argument will load the corresponding
+ environment. Example: <tt>rails console production</tt>.
+
+To reload your controllers and models after launching the console run
+<tt>reload!</tt>
+
+More information about irb can be found at:
+link:http://www.rubycentral.com/pickaxe/irb.html
+
+
+== dbconsole
+
+You can go to the command line of your database directly through <tt>rails
+dbconsole</tt>. You would be connected to the database with the credentials
+defined in database.yml. Starting the script without arguments will connect you
+to the development database. Passing an argument will connect you to a different
+database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
+PostgreSQL and SQLite 3.
+
+== Description of Contents
+
+The default directory structure of a generated Ruby on Rails application:
+
+ |-- app
+ | |-- controllers
+ | |-- helpers
+ | |-- models
+ | `-- views
+ | `-- layouts
+ |-- config
+ | |-- environments
+ | |-- initializers
+ | `-- locales
+ |-- db
+ |-- doc
+ |-- lib
+ | `-- tasks
+ |-- log
+ |-- public
+ | |-- images
+ | |-- javascripts
+ | `-- stylesheets
+ |-- script
+ | `-- performance
+ |-- test
+ | |-- fixtures
+ | |-- functional
+ | |-- integration
+ | |-- performance
+ | `-- unit
+ |-- tmp
+ | |-- cache
+ | |-- pids
+ | |-- sessions
+ | `-- sockets
+ `-- vendor
+ `-- plugins
+
+app
+ Holds all the code that's specific to this particular application.
+
+app/controllers
+ Holds controllers that should be named like weblogs_controller.rb for
+ automated URL mapping. All controllers should descend from
+ ApplicationController which itself descends from ActionController::Base.
+
+app/models
+ Holds models that should be named like post.rb. Models descend from
+ ActiveRecord::Base by default.
+
+app/views
+ Holds the template files for the view that should be named like
+ weblogs/index.html.erb for the WeblogsController#index action. All views use
+ eRuby syntax by default.
+
+app/views/layouts
+ Holds the template files for layouts to be used with views. This models the
+ common header/footer method of wrapping views. In your views, define a layout
+ using the <tt>layout :default</tt> and create a file named default.html.erb.
+ Inside default.html.erb, call <% yield %> to render the view using this
+ layout.
+
+app/helpers
+ Holds view helpers that should be named like weblogs_helper.rb. These are
+ generated for you automatically when using generators for controllers.
+ Helpers can be used to wrap functionality for your views into methods.
+
+config
+ Configuration files for the Rails environment, the routing map, the database,
+ and other dependencies.
+
+db
+ Contains the database schema in schema.rb. db/migrate contains all the
+ sequence of Migrations for your schema.
+
+doc
+ This directory is where your application documentation will be stored when
+ generated using <tt>rake doc:app</tt>
+
+lib
+ Application specific libraries. Basically, any kind of custom code that
+ doesn't belong under controllers, models, or helpers. This directory is in
+ the load path.
+
+public
+ The directory available for the web server. Contains subdirectories for
+ images, stylesheets, and javascripts. Also contains the dispatchers and the
+ default HTML files. This should be set as the DOCUMENT_ROOT of your web
+ server.
+
+script
+ Helper scripts for automation and generation.
+
+test
+ Unit and functional tests along with fixtures. When using the rails generate
+ command, template test files will be generated for you and placed in this
+ directory.
+
+vendor
+ External libraries that the application depends on. Also includes the plugins
+ subdirectory. If the app has frozen rails, those gems also go here, under
+ vendor/rails/. This directory is in the load path.
View
7 episode-220/store/Rakefile
@@ -0,0 +1,7 @@
+# Add your own tasks in files placed in lib/tasks ending in .rake,
+# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
+
+require File.expand_path('../config/application', __FILE__)
+require 'rake'
+
+Rails::Application.load_tasks
View
4 episode-220/store/app/controllers/application_controller.rb
@@ -0,0 +1,4 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+ layout 'application'
+end
View
5 episode-220/store/app/controllers/carts_controller.rb
@@ -0,0 +1,5 @@
+class CartsController < ApplicationController
+ def show
+ @cart = current_cart
+ end
+end
View
44 episode-220/store/app/controllers/categories_controller.rb
@@ -0,0 +1,44 @@
+class CategoriesController < ApplicationController
+ def index
+ @categories = Category.find(:all)
+ end
+
+ def show
+ @category = Category.find(params[:id])
+ end
+
+ def new
+ @category = Category.new
+ end
+
+ def create
+ @category = Category.new(params[:category])
+ if @category.save
+ flash[:notice] = "Successfully created category."
+ redirect_to @category
+ else
+ render :action => 'new'
+ end
+ end
+
+ def edit
+ @category = Category.find(params[:id])
+ end
+
+ def update
+ @category = Category.find(params[:id])
+ if @category.update_attributes(params[:category])
+ flash[:notice] = "Successfully updated category."
+ redirect_to @category
+ else
+ render :action => 'edit'
+ end
+ end
+
+ def destroy
+ @category = Category.find(params[:id])
+ @category.destroy
+ flash[:notice] = "Successfully destroyed category."
+ redirect_to categories_url
+ end
+end
View
8 episode-220/store/app/controllers/line_items_controller.rb
@@ -0,0 +1,8 @@
+class LineItemsController < ApplicationController
+ def create
+ @product = Product.find(params[:product_id])
+ @line_item = LineItem.create!(:cart => current_cart, :product => @product, :quantity => 1, :unit_price => @product.price)
+ flash[:notice] = "Added #{@product.name} to cart."
+ redirect_to current_cart_url
+ end
+end
View
23 episode-220/store/app/controllers/orders_controller.rb
@@ -0,0 +1,23 @@
+class OrdersController < ApplicationController
+ def show
+ @order = Order.find(params[:id])
+ end
+
+ def new
+ @order = Order.new
+ end
+
+ def create
+ @order = current_cart.build_order(params[:order])
+ @order.ip_address = request.remote_ip
+ if @order.save
+ if @order.purchase
+ render :action => "success"
+ else
+ render :action => "failure"
+ end
+ else
+ render :action => 'new'
+ end
+ end
+end
View
44 episode-220/store/app/controllers/products_controller.rb
@@ -0,0 +1,44 @@
+class ProductsController < ApplicationController
+ def index
+ @products = Product.all
+ end
+
+ def show
+ @product = Product.find(params[:id])
+ end
+
+ def new
+ @product = Product.new
+ end
+
+ def create
+ @product = Product.new(params[:product])
+ if @product.save
+ flash[:notice] = "Successfully created product."
+ redirect_to @product
+ else
+ render :action => 'new'
+ end
+ end
+
+ def edit
+ @product = Product.find(params[:id])
+ end
+
+ def update
+ @product = Product.find(params[:id])
+ if @product.update_attributes(params[:product])
+ flash[:notice] = "Successfully updated product."
+ redirect_to @product
+ else
+ render :action => 'edit'
+ end
+ end
+
+ def destroy
+ @product = Product.find(params[:id])
+ @product.destroy
+ flash[:notice] = "Successfully destroyed product."
+ redirect_to products_url
+ end
+end
View
2  episode-220/store/app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
View
2  episode-220/store/app/helpers/carts_helper.rb
@@ -0,0 +1,2 @@
+module CartsHelper
+end
View
2  episode-220/store/app/helpers/categories_helper.rb
@@ -0,0 +1,2 @@
+module CategoriesHelper
+end
View
23 episode-220/store/app/helpers/error_messages_helper.rb
@@ -0,0 +1,23 @@
+module ErrorMessagesHelper
+ # Render error messages for the given objects. The :message and :header_message options are allowed.
+ def error_messages_for(*objects)
+ options = objects.extract_options!
+ options[:header_message] ||= "Invalid Fields"
+ options[:message] ||= "Correct the following errors and try again."
+ messages = objects.compact.map { |o| o.errors.full_messages }.flatten
+ unless messages.empty?
+ content_tag(:div, :class => "error_messages") do
+ list_items = messages.map { |msg| content_tag(:li, msg) }
+ content_tag(:h2, options[:header_message]) + content_tag(:p, options[:message]) + content_tag(:ul, list_items.join.html_safe)
+ end
+ end
+ end
+
+ module FormBuilderAdditions
+ def error_messages(options = {})
+ @template.error_messages_for(@object, options)
+ end
+ end
+end
+
+ActionView::Helpers::FormBuilder.send(:include, ErrorMessagesHelper::FormBuilderAdditions)
View
22 episode-220/store/app/helpers/layout_helper.rb
@@ -0,0 +1,22 @@
+# These helper methods can be called in your template to set variables to be used in the layout
+# This module should be included in all views globally,
+# to do so you may need to add this line to your ApplicationController
+# helper :layout
+module LayoutHelper
+ def title(page_title, show_title = true)
+ content_for(:title) { page_title.to_s }
+ @show_title = show_title
+ end
+
+ def show_title?
+ @show_title
+ end
+
+ def stylesheet(*args)
+ content_for(:head) { stylesheet_link_tag(*args) }
+ end
+
+ def javascript(*args)
+ content_for(:head) { javascript_include_tag(*args) }
+ end
+end
View
2  episode-220/store/app/helpers/line_items_helper.rb
@@ -0,0 +1,2 @@
+module LineItemsHelper
+end
View
2  episode-220/store/app/helpers/orders_helper.rb
@@ -0,0 +1,2 @@
+module OrdersHelper
+end
View
2  episode-220/store/app/helpers/products_helper.rb
@@ -0,0 +1,2 @@
+module ProductsHelper
+end
View
9 episode-220/store/app/models/cart.rb
@@ -0,0 +1,9 @@
+class Cart < ActiveRecord::Base
+ has_many :line_items
+ has_one :order
+
+ def total_price
+ # convert to array so it doesn't try to do sum on database directly
+ line_items.to_a.sum(&:full_price)
+ end
+end
View
3  episode-220/store/app/models/category.rb
@@ -0,0 +1,3 @@
+class Category < ActiveRecord::Base
+ has_many :products
+end
View
8 episode-220/store/app/models/line_item.rb
@@ -0,0 +1,8 @@
+class LineItem < ActiveRecord::Base
+ belongs_to :cart
+ belongs_to :product
+
+ def full_price
+ unit_price * quantity
+ end
+end
View
55 episode-220/store/app/models/order.rb
@@ -0,0 +1,55 @@
+class Order < ActiveRecord::Base
+ belongs_to :cart
+ has_many :transactions, :class_name => "OrderTransaction"
+
+ attr_accessor :card_number, :card_verification
+
+ validate :validate_card, :on => :create
+
+ def purchase
+ response = GATEWAY.purchase(price_in_cents, credit_card, purchase_options)
+ transactions.create!(:action => "purchase", :amount => price_in_cents, :response => response)
+ cart.update_attribute(:purchased_at, Time.now) if response.success?
+ response.success?
+ end
+
+ def price_in_cents
+ (cart.total_price*100).round
+ end
+
+ private
+
+ def purchase_options
+ {
+ :ip => ip_address,
+ :billing_address => {
+ :name => "Ryan Bates",
+ :address1 => "123 Main St.",
+ :city => "New York",
+ :state => "NY",
+ :country => "US",
+ :zip => "10001"
+ }
+ }
+ end
+
+ def validate_card
+ unless credit_card.valid?
+ credit_card.errors.full_messages.each do |message|
+ errors.add_to_base message
+ end
+ end
+ end
+
+ def credit_card
+ @credit_card ||= ActiveMerchant::Billing::CreditCard.new(
+ :type => card_type,
+ :number => card_number,
+ :verification_value => card_verification,
+ :month => card_expires_on.month,
+ :year => card_expires_on.year,
+ :first_name => first_name,
+ :last_name => last_name
+ )
+ end
+end
View
16 episode-220/store/app/models/order_transaction.rb
@@ -0,0 +1,16 @@
+class OrderTransaction < ActiveRecord::Base
+ belongs_to :order
+ serialize :params
+
+ def response=(response)
+ self.success = response.success?
+ self.authorization = response.authorization
+ self.message = response.message
+ self.params = response.params
+ rescue ActiveMerchant::ActiveMerchantError => e
+ self.success = false
+ self.authorization = nil
+ self.message = e.message
+ self.params = {}
+ end
+end
View
3  episode-220/store/app/models/product.rb
@@ -0,0 +1,3 @@
+class Product < ActiveRecord::Base
+ belongs_to :category
+end
View
4 episode-220/store/app/views/carts/purchase.html.erb
@@ -0,0 +1,4 @@
+<% title "Purchase Successful" %>
+
+<p><strong>Thank you for your order!</strong> We will process it within one business day.</p>
+<p><%= link_to "Back to Products", products_path %></p>
View
28 episode-220/store/app/views/carts/show.html.erb
@@ -0,0 +1,28 @@
+<% title "Shopping Cart" %>
+
+<table id="line_items">
+ <tr>
+ <th>Product</th>
+ <th>Qty</th>
+ <th class="price">Unit Price</th>
+ <th class="price">Full Price</th>
+ </tr>
+ <% for line_item in @cart.line_items %>
+ <tr class="<%= cycle :odd, :even %>">
+ <td><%=h line_item.product.name %></td>
+ <td class="qty"><%= line_item.quantity %></td>
+ <td class="price"><%= number_to_currency(line_item.unit_price) %></td>
+ <td class="price"><%= number_to_currency(line_item.full_price) %></td>
+ </tr>
+ <% end %>
+ <tr>
+ <td class="total price" colspan="4">
+ Total: <%= number_to_currency @cart.total_price %>
+ </td>
+ </tr>
+</table>
+
+<p>
+ <%= link_to "Continue Shopping", products_path %> |
+ <%= link_to "Checkout", new_order_path %>
+</p>
View
7 episode-220/store/app/views/categories/_form.html.erb
@@ -0,0 +1,7 @@
+<% form_for @category do |f| %>
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p><%= f.submit "Submit" %></p>
+<% end %>
View
8 episode-220/store/app/views/categories/edit.html.erb
@@ -0,0 +1,8 @@
+<% title "Edit Category" %>
+
+<%= render :partial => 'form' %>
+
+<p>
+ <%= link_to "Show", @category %> |
+ <%= link_to "View All", categories_path %>
+</p>
View
13 episode-220/store/app/views/categories/index.html.erb
@@ -0,0 +1,13 @@
+<% title "Categories" %>
+
+<% for category in @categories %>
+ <div class="category">
+ <h3><%= link_to h(category.name), category %></h3>
+ <div class="actions">
+ <%= link_to "Edit", edit_category_path(category) %> |
+ <%= link_to "Destroy", category, :confirm => 'Are you sure?', :method => :delete %>
+ </div>
+ </div>
+<% end %>
+
+<p><%= link_to "New Category", new_category_path %></p>
View
5 episode-220/store/app/views/categories/new.html.erb
@@ -0,0 +1,5 @@
+<% title "New Category" %>
+
+<%= render :partial => 'form' %>
+
+<p><%= link_to "Back to List", categories_path %></p>
View
13 episode-220/store/app/views/categories/show.html.erb
@@ -0,0 +1,13 @@
+<% title @category.name %>
+
+<ul>
+<% for product in @category.products %>
+ <li><%= link_to h(product.name), product %></li>
+<% end %>
+</ul>
+
+<p>
+ <%= link_to "Edit", edit_category_path(@category) %> |
+ <%= link_to "Destroy", @category, :confirm => 'Are you sure?', :method => :delete %> |
+ <%= link_to "View All", categories_path %>
+</p>
View
22 episode-220/store/app/views/layouts/application.html.erb
@@ -0,0 +1,22 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html>
+ <head>
+ <title><%= h(yield(:title) || "Untitled") %></title>
+ <%= stylesheet_link_tag 'application', :media => "all" %>
+ <%= yield(:head) %>
+ </head>
+ <body>
+ <div id="container">
+ <%- flash.each do |name, msg| -%>
+ <%= content_tag :div, msg, :id => "flash_#{name}" %>
+ <%- end -%>
+
+ <%- if show_title? -%>
+ <h1><%=h yield(:title) %></h1>
+ <%- end -%>
+
+ <%= yield %>
+ </div>
+ </body>
+</html>
View
1  episode-220/store/app/views/orders/failure.html.erb
@@ -0,0 +1 @@
+FAILURE
View
32 episode-220/store/app/views/orders/new.html.erb
@@ -0,0 +1,32 @@
+<% title "New Order" %>
+
+<% form_for @order do |f| %>
+ <%= f.error_messages %>
+ <p>
+ <%= f.label :first_name %><br />
+ <%= f.text_field :first_name %>
+ </p>
+ <p>
+ <%= f.label :last_name %><br />
+ <%= f.text_field :last_name %>
+ </p>
+ <p>
+ <%= f.label :card_type %><br />
+ <%= f.select :card_type, [["Visa", "visa"], ["MasterCard", "master"], ["Discover", "discover"], ["American Express", "american_express"]] %>
+ </p>
+ <p>
+ <%= f.label :card_number %><br />
+ <%= f.text_field :card_number %>
+ </p>
+ <p>
+ <%= f.label :card_verification, "Card Verification Value (CVV)" %><br />
+ <%= f.text_field :card_verification %>
+ </p>
+ <p>
+ <%= f.label :card_expires_on %><br />
+ <%= f.date_select :card_expires_on, :discard_day => true, :start_year => Date.today.year, :end_year => (Date.today.year+10), :add_month_numbers => true %>
+ </p>
+ <p><%= f.submit "Submit" %></p>
+<% end %>
+
+
View
29 episode-220/store/app/views/orders/show.html.erb
@@ -0,0 +1,29 @@
+<% title "Order ##{@order.id}" %>
+
+<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
+<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
+<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
+<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
+
+<table id="line_items">
+ <tr>
+ <th>Product</th>
+ <th>Qty</th>
+ <th class="price">Unit Price</th>
+ <th class="price">Full Price</th>
+ </tr>
+ <% for line_item in @order.cart.line_items %>
+ <tr class="<%= cycle :odd, :even %>">
+ <td><%= line_item.product.name %></td>
+ <td class="qty"><%= line_item.quantity %></td>
+ <td class="price"><%= number_to_currency(line_item.unit_price) %></td>
+ <td class="price"><%= number_to_currency(line_item.full_price) %></td>
+ </tr>
+ <% end %>
+ <tr>
+ <td class="total price" colspan="4">
+ Total: <%= number_to_currency @order.cart.total_price %>
+ </td>
+ </tr>
+</table>
+<p id="pdf_link"><%= link_to "Download Invoice (PDF)", order_path(@order, :format => "pdf") %></p>
View
1  episode-220/store/app/views/orders/success.html.erb
@@ -0,0 +1 @@
+SUCCESS!
View
20 episode-220/store/app/views/products/_form.html.erb
@@ -0,0 +1,20 @@
+<%= form_for @product do |f| %>
+ <%= f.error_messages %>
+ <p>
+ <%= f.label :category_id %><br />
+ <%= f.text_field :category_id %>
+ </p>
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.label :price %><br />
+ <%= f.text_field :price %>
+ </p>
+ <p>
+ <%= f.label :description %><br />
+ <%= f.text_area :description %>
+ </p>
+ <p><%= f.submit %></p>
+<% end %>
View
8 episode-220/store/app/views/products/edit.html.erb
@@ -0,0 +1,8 @@
+<% title "Edit Product" %>
+
+<%= render 'form' %>
+
+<p>
+ <%= link_to "Show", @product %> |
+ <%= link_to "View All", products_path %>
+</p>
View
17 episode-220/store/app/views/products/index.html.erb
@@ -0,0 +1,17 @@
+<% title "Products" %>
+
+<div id="products">
+<% for product in @products %>
+ <div class="product">
+ <h3>
+ <%= link_to h(product.name), product %>
+ <%= number_to_currency(product.price) %>
+ </h3>
+ <div class="actions">
+ <%= link_to "Edit", edit_product_path(product) %> |
+ <%= link_to "Destroy", product, :confirm => 'Are you sure?', :method => :delete %>
+ </div>
+ </div>
+<% end %>
+ <p class="actions"><%= link_to "New Product", new_product_path %></p>
+</div>
View
5 episode-220/store/app/views/products/new.html.erb
@@ -0,0 +1,5 @@
+<% title "New Product" %>
+
+<%= render 'form' %>
+
+<p><%= link_to "Back to List", products_path %></p>
View
24 episode-220/store/app/views/products/show.html.erb
@@ -0,0 +1,24 @@
+<% title "Product" %>
+
+<p>
+ <strong>Category:</strong>
+ <%= @product.category_id %>
+</p>
+<p>
+ <strong>Name:</strong>
+ <%= @product.name %>
+</p>
+<p>
+ <strong>Price:</strong>
+ <%= @product.price %>
+</p>
+<p>
+ <strong>Description:</strong>
+ <%= @product.description %>
+</p>
+
+<p>
+ <%= link_to "Edit", edit_product_path(@product) %> |
+ <%= link_to "Destroy", @product, :confirm => 'Are you sure?', :method => :delete %> |
+ <%= link_to "View All", products_path %>
+</p>
View
4 episode-220/store/config.ru
@@ -0,0 +1,4 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+run Store::Application
View
47 episode-220/store/config/application.rb
@@ -0,0 +1,47 @@
+require File.expand_path('../boot', __FILE__)
+
+require 'rails/all'
+
+# If you have a Gemfile, require the gems listed there, including any gems
+# you've limited to :test, :development, or :production.
+Bundler.require(:default, Rails.env) if defined?(Bundler)
+
+module Store
+ class Application < Rails::Application
+ # 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.
+
+ # Add additional load paths for your own custom dirs
+ # config.load_paths += %W( #{config.root}/extras )
+
+ # Only load the plugins named here, in the order given (default is alphabetical).
+ # :all can be used as a placeholder for all plugins not explicitly named
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
+
+ # Activate observers that should always be running
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
+
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
+ # config.time_zone = 'Central Time (US & Canada)'
+
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
+ # config.i18n.default_locale = :de
+
+ # Configure generators values. Many other options are available, be sure to check the documentation.
+ # config.generators do |g|
+ # g.orm :active_record
+ # g.template_engine :erb
+ # g.test_framework :test_unit, :fixture => true
+ # end
+
+ # Configure the default encoding used in templates for Ruby 1.9.
+ config.encoding = "utf-8"
+
+ # Configure sensitive parameters which will be filtered from the log file.
+ config.filter_parameters += [:password]
+ config.middleware.use "PDFKit::Middleware", :print_media_type => true
+ end
+end
View
13 episode-220/store/config/boot.rb
@@ -0,0 +1,13 @@
+require 'rubygems'
+
+# Set up gems listed in the Gemfile.
+gemfile = File.expand_path('../../Gemfile', __FILE__)
+begin
+ ENV['BUNDLE_GEMFILE'] = gemfile
+ require 'bundler'
+ Bundler.setup
+rescue Bundler::GemNotFound => e
+ STDERR.puts e.message
+ STDERR.puts "Try running `bundle install`."
+ exit!
+end if File.exist?(gemfile)
View
22 episode-220/store/config/database.yml
@@ -0,0 +1,22 @@
+# SQLite version 3.x
+# gem install sqlite3-ruby (not necessary on OS X Leopard)
+development:
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
+ timeout: 5000
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: sqlite3
+ database: db/test.sqlite3
+ pool: 5
+ timeout: 5000
+
+production:
+ adapter: sqlite3
+ database: db/production.sqlite3
+ pool: 5
+ timeout: 5000
View
5 episode-220/store/config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application
+Store::Application.initialize!
View
19 episode-220/store/config/environments/development.rb
@@ -0,0 +1,19 @@
+Store::Application.configure do
+ # 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.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
+end
View
46 episode-220/store/config/environments/production.rb
@@ -0,0 +1,46 @@
+Store::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # The production environment is meant for finished, "live" apps.
+ # Code is not reloaded between requests
+ config.cache_classes = true
+
+ # Full error reports are disabled and caching is turned on
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # Specifies the header that your server uses for sending files
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
+
+ # For nginx:
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
+
+ # If you have no front-end server that supports something like X-Sendfile,
+ # just comment this out and Rails will serve the files
+
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
+
+ # Use a different logger for distributed setups
+ # config.logger = SyslogLogger.new
+
+ # Use a different cache store in production
+ # config.cache_store = :mem_cache_store
+
+ # Disable Rails's static asset server
+ # In production, Apache or nginx will already do this
+ config.serve_static_assets = false
+
+ # Enable serving of images, stylesheets, and javascripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Disable delivery errors, bad email addresses will be ignored
+ # config.action_mailer.raise_delivery_errors = false
+
+ # Enable threaded mode
+ # config.threadsafe!
+
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
+ # the I18n.default_locale when a translation can not be found)
+ config.i18n.fallbacks = true
+end
View
32 episode-220/store/config/environments/test.rb
@@ -0,0 +1,32 @@
+Store::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # The test environment is used exclusively to run your application's
+ # test suite. You never need to work with it otherwise. Remember that
+ # your test database is "scratch space" for the test suite and is wiped
+ # and recreated between test runs. Don't rely on the data there!
+ config.cache_classes = true
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_controller.perform_caching = false
+
+ # Raise exceptions instead of rendering exception templates
+ config.action_dispatch.show_exceptions = false
+
+ # Disable request forgery protection in test environment
+ config.action_controller.allow_forgery_protection = false
+
+ # Tell Action Mailer not to deliver emails to the real world.
+ # The :test delivery method accumulates sent emails in the
+ # ActionMailer::Base.deliveries array.
+ config.action_mailer.delivery_method = :test
+
+ # 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
+end
View
7 episode-220/store/config/initializers/backtrace_silencers.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
+# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
+
+# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
+# Rails.backtrace_cleaner.remove_silencers!
View
10 episode-220/store/config/initializers/inflections.rb
@@ -0,0 +1,10 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new inflection rules using the following format
+# (all these examples are active by default):
+# ActiveSupport::Inflector.inflections do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
View
5 episode-220/store/config/initializers/mime_types.rb
@@ -0,0 +1,5 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new mime types for use in respond_to blocks:
+# Mime::Type.register "text/richtext", :rtf
+# Mime::Type.register_alias "text/html", :iphone
View
7 episode-220/store/config/initializers/secret_token.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies 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.
+Rails.application.config.secret_token = 'af106ea5ae13197eb7eeb98cf356a29f54e526dfe1e7735d103757960670c7b655fa4f118ba3c909808d1c25bbd3f0cb8f72170f34fe6a912c073bfd4a301c30'
View
8 episode-220/store/config/initializers/session_store.rb
@@ -0,0 +1,8 @@
+# Be sure to restart your server when you modify this file.
+
+Rails.application.config.session_store :cookie_store, :key => '_store_session'
+
+# 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")
+# Rails.application.config.session_store :active_record_store
View
5 episode-220/store/config/locales/en.yml
@@ -0,0 +1,5 @@
+# Sample localization file for English. Add more files in this directory for other locales.
+# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+
+en:
+ hello: "Hello world"
View
8 episode-220/store/config/routes.rb
@@ -0,0 +1,8 @@
+Store::Application.routes.draw do |map|
+ resources :orders
+ resources :line_items
+ resources :carts
+ resources :products
+ resources :categories
+ root :to => "products#index"
+end
View
12 episode-220/store/db/migrate/20080621194238_create_categories.rb
@@ -0,0 +1,12 @@
+class CreateCategories < ActiveRecord::Migration
+ def self.up
+ create_table :categories do |t|
+ t.string :name
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :categories
+ end
+end
View
15 episode-220/store/db/migrate/20080621194423_create_products.rb
@@ -0,0 +1,15 @@
+class CreateProducts < ActiveRecord::Migration
+ def self.up
+ create_table :products do |t|
+ t.belongs_to :category
+ t.string :name
+ t.decimal :price
+ t.text :description
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :products
+ end
+end
View
12 episode-220/store/db/migrate/20081221210944_create_carts.rb
@@ -0,0 +1,12 @@
+class CreateCarts < ActiveRecord::Migration
+ def self.up
+ create_table :carts do |t|
+ t.datetime :purchased_at
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :carts
+ end
+end
View
15 episode-220/store/db/migrate/20081221211031_create_line_items.rb
@@ -0,0 +1,15 @@
+class CreateLineItems < ActiveRecord::Migration
+ def self.up
+ create_table :line_items do |t|
+ t.decimal :unit_price
+ t.integer :product_id
+ t.integer :cart_id
+ t.integer :quantity
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :line_items
+ end
+end
View
17 episode-220/store/db/migrate/20090119051232_create_orders.rb
@@ -0,0 +1,17 @@
+class CreateOrders < ActiveRecord::Migration
+ def self.up
+ create_table :orders do |t|
+ t.integer :cart_id
+ t.string :ip_address
+ t.string :first_name
+ t.string :last_name
+ t.string :card_type
+ t.date :card_expires_on
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :orders
+ end
+end
View
19 episode-220/store/db/migrate/20090119062501_create_order_transactions.rb
@@ -0,0 +1,19 @@
+class CreateOrderTransactions < ActiveRecord::Migration
+ def self.up
+ create_table :order_transactions do |t|
+ t.integer :order_id
+ t.string :action
+ t.integer :amount
+ t.boolean :success
+ t.string :authorization
+ t.string :message
+ t.text :params
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :order_transactions
+ end
+end
View
67 episode-220/store/db/schema.rb
@@ -0,0 +1,67 @@
+# This file is auto-generated from the current state of the database. Instead of editing this file,
+# please use the migrations feature of Active Record to incrementally modify your database, and
+# then regenerate this schema definition.
+#
+# Note that this schema.rb definition is the authoritative source for your database schema. If you need
+# to create the application database on another system, you should be using db:schema:load, not running
+# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
+# you'll amass, the slower it'll run and the greater likelihood for issues).
+#
+# It's strongly recommended to check this file into your version control system.
+
+ActiveRecord::Schema.define(:version => 20090119062501) do
+
+ create_table "carts", :force => true do |t|
+ t.datetime "purchased_at"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "categories", :force => true do |t|
+ t.string "name"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "line_items", :force => true do |t|
+ t.decimal "unit_price"
+ t.integer "product_id"
+ t.integer "cart_id"
+ t.integer "quantity"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "order_transactions", :force => true do |t|
+ t.integer "order_id"
+ t.string "action"
+ t.integer "amount"
+ t.boolean "success"
+ t.string "authorization"
+ t.string "message"
+ t.text "params"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "orders", :force => true do |t|
+ t.integer "cart_id"
+ t.string "ip_address"
+ t.string "first_name"
+ t.string "last_name"
+ t.string "card_type"
+ t.date "card_expires_on"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "products", :force => true do |t|
+ t.integer "category_id"
+ t.string "name"
+ t.decimal "price"
+ t.text "description"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+end
View
7 episode-220/store/db/seeds.rb
@@ -0,0 +1,7 @@
+# This file should contain all the record creation needed to seed the database with its default values.
+# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
+#
+# Examples:
+#
+# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
+# Mayor.create(:name => 'Daley', :city => cities.first)
View
2  episode-220/store/doc/README_FOR_APP
@@ -0,0 +1,2 @@
+Use this README file to introduce your application and point to useful places in the API for learning more.
+Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
View
0  episode-220/store/lib/tasks/.gitkeep
No changes.
View
26 episode-220/store/public/404.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The page you were looking for doesn't exist (404)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/404.html -->
+ <div class="dialog">
+ <h1>The page you were looking for doesn't exist.</h1>
+ <p>You may have mistyped the address or the page may have moved.</p>
+ </div>
+</body>
+</html>
View
26 episode-220/store/public/422.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The change you wanted was rejected (422)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/422.html -->
+ <div class="dialog">
+ <h1>The change you wanted was rejected.</h1>
+ <p>Maybe you tried to change something you didn't have access to.</p>
+ </div>
+</body>
+</html>
View
26 episode-220/store/public/500.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>We're sorry, but something went wrong (500)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/500.html -->
+ <div class="dialog">
+ <h1>We're sorry, but something went wrong.</h1>
+ <p>We've been notified about this issue and we'll take a look at it shortly.</p>
+ </div>
+</body>
+</html>
View
0  episode-220/store/public/favicon.ico
No changes.
View
BIN  episode-220/store/public/images/rails.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
2  episode-220/store/public/javascripts/application.js
@@ -0,0 +1,2 @@
+// Place your application-specific JavaScript functions and classes here
+// This file is automatically included by javascript_include_tag :defaults
View
965 episode-220/store/public/javascripts/controls.js
@@ -0,0 +1,965 @@
+// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
+// Contributors:
+// Richard Livsey
+// Rahul Bhargava
+// Rob Wills
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// Autocompleter.Base handles all the autocompletion functionality
+// that's independent of the data source for autocompletion. This
+// includes drawing the autocompletion menu, observing keyboard
+// and mouse events, and similar.
+//
+// Specific autocompleters need to provide, at the very least,
+// a getUpdatedChoices function that will be invoked every time
+// the text inside the monitored textbox changes. This method
+// should get the text for which to provide autocompletion by
+// invoking this.getToken(), NOT by directly accessing
+// this.element.value. This is to allow incremental tokenized
+// autocompletion. Specific auto-completion logic (AJAX, etc)
+// belongs in getUpdatedChoices.
+//
+// Tokenized incremental autocompletion is enabled automatically
+// when an autocompleter is instantiated with the 'tokens' option
+// in the options parameter, e.g.:
+// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
+// will incrementally autocomplete with a comma as the token.
+// Additionally, ',' in the above example can be replaced with
+// a token array, e.g. { tokens: [',', '\n'] } which
+// enables autocompletion on multiple tokens. This is most
+// useful when one of the tokens is \n (a newline), as it
+// allows smart autocompletion after linebreaks.
+
+if(typeof Effect == 'undefined')
+ throw("controls.js requires including script.aculo.us' effects.js library");
+
+var Autocompleter = { };
+Autocompleter.Base = Class.create({
+ baseInitialize: function(element, update, options) {
+ element = $(element);
+ this.element = element;
+ this.update = $(update);
+ this.hasFocus = false;
+ this.changed = false;
+ this.active = false;
+ this.index = 0;
+ this.entryCount = 0;
+ this.oldElementValue = this.element.value;
+
+ if(this.setOptions)
+ this.setOptions(options);
+ else
+ this.options = options || { };
+
+ this.options.paramName = this.options.paramName || this.element.name;
+ this.options.tokens = this.options.tokens || [];
+ this.options.frequency = this.options.frequency || 0.4;
+ this.options.minChars = this.options.minChars || 1;
+ this.options.onShow = this.options.onShow ||
+ function(element, update){
+ if(!update.style.position || update.style.position=='absolute') {
+ update.style.position = 'absolute';
+ Position.clone(element, update, {
+ setHeight: false,
+ offsetTop: element.offsetHeight
+ });
+ }
+ Effect.Appear(update,{duration:0.15});
+ };
+ this.options.onHide = this.options.onHide ||
+ function(element, update){ new Effect.Fade(update,{duration:0.15}) };
+
+ if(typeof(this.options.tokens) == 'string')
+ this.options.tokens = new Array(this.options.tokens);
+ // Force carriage returns as token delimiters anyway
+ if (!this.options.tokens.include('\n'))
+ this.options.tokens.push('\n');
+
+ this.observer = null;
+
+ this.element.setAttribute('autocomplete','off');
+
+ Element.hide(this.update);
+
+ Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
+ Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
+ },
+
+ show: function() {
+ if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
+ if(!this.iefix &&
+ (Prototype.Browser.IE) &&
+ (Element.getStyle(this.update, 'position')=='absolute')) {
+ new Insertion.After(this.update,
+ '<iframe id="' + this.update.id + '_iefix" '+
+ 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
+ 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
+ this.iefix = $(this.update.id+'_iefix');
+ }
+ if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
+ },
+
+ fixIEOverlapping: function() {
+ Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
+ this.iefix.style.zIndex = 1;
+ this.update.style.zIndex = 2;
+ Element.show(this.iefix);
+ },
+
+ hide: function() {
+ this.stopIndicator();
+ if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
+ if(this.iefix) Element.hide(this.iefix);
+ },
+
+ startIndicator: function() {
+ if(this.options.indicator) Element.show(this.options.indicator);
+ },
+
+ stopIndicator: function() {
+ if(this.options.indicator) Element.hide(this.options.indicator);
+ },
+
+ onKeyPress: function(event) {
+ if(this.active)
+ switch(event.keyCode) {
+ case Event.KEY_TAB:
+ case Event.KEY_RETURN:
+ this.selectEntry();
+ Event.stop(event);
+ case Event.KEY_ESC:
+ this.hide();
+ this.active = false;
+ Event.stop(event);
+ return;
+ case Event.KEY_LEFT:
+ case Event.KEY_RIGHT:
+ return;
+ case Event.KEY_UP:
+ this.markPrevious();
+ this.render();
+ Event.stop(event);
+ return;
+ case Event.KEY_DOWN:
+ this.markNext();
+ this.render();
+ Event.stop(event);
+ return;
+ }
+ else
+ if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
+ (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
+
+ this.changed = true;
+ this.hasFocus = true;
+
+ if(this.observer) clearTimeout(this.observer);
+ this.observer =
+ setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
+ },
+
+ activate: function() {
+ this.changed = false;
+ this.hasFocus = true;
+ this.getUpdatedChoices();
+ },
+
+ onHover: function(event) {
+ var element = Event.findElement(event, 'LI');
+ if(this.index != element.autocompleteIndex)
+ {
+ this.index = element.autocompleteIndex;
+ this.render();
+ }
+ Event.stop(event);
+ },
+
+ onClick: function(event) {
+ var element = Event.findElement(event, 'LI');
+ this.index = element.autocompleteIndex;
+ this.selectEntry();
+ this.hide();
+ },
+
+ onBlur: function(event) {
+ // needed to make click events working
+ setTimeout(this.hide.bind(this), 250);
+ this.hasFocus = false;
+ this.active = false;
+ },
+
+ render: function() {
+ if(this.entryCount > 0) {
+ for (var i = 0; i < this.entryCount; i++)
+ this.index==i ?
+ Element.addClassName(this.getEntry(i),"selected") :
+ Element.removeClassName(this.getEntry(i),"selected");
+ if(this.hasFocus) {
+ this.show();
+ this.active = true;
+ }
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ },
+
+ markPrevious: function() {
+ if(this.index > 0) this.index--;
+ else this.index = this.entryCount-1;
+ this.getEntry(this.index).scrollIntoView(true);
+ },
+
+ markNext: function() {
+ if(this.index < this.entryCount-1) this.index++;
+ else this.index = 0;
+ this.getEntry(this.index).scrollIntoView(false);
+ },
+
+ getEntry: function(index) {
+ return this.update.firstChild.childNodes[index];
+ },
+
+ getCurrentEntry: function() {
+ return this.getEntry(this.index);
+ },
+
+ selectEntry: function() {
+ this.active = false;
+ this.updateElement(this.getCurrentEntry());
+ },
+
+ updateElement: function(selectedElement) {
+ if (this.options.updateElement) {
+ this.options.updateElement(selectedElement);
+ return;
+ }
+ var value = '';
+ if (this.options.select) {
+ var nodes = $(selectedElement).select('.' + this.options.select) || [];
+ if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
+ } else
+ value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
+
+ var bounds = this.getTokenBounds();
+ if (bounds[0] != -1) {
+ var newValue = this.element.value.substr(0, bounds[0]);
+ var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
+ if (whitespace)
+ newValue += whitespace[0];
+ this.element.value = newValue + value + this.element.value.substr(bounds[1]);
+ } else {
+ this.element.value = value;
+ }
+ this.oldElementValue = this.element.value;
+ this.element.focus();
+
+ if (this.options.afterUpdateElement)
+ this.options.afterUpdateElement(this.element, selectedElement);
+ },
+
+ updateChoices: function(choices) {
+ if(!this.changed && this.hasFocus) {
+ this.update.innerHTML = choices;
+ Element.cleanWhitespace(this.update);
+ Element.cleanWhitespace(this.update.down());
+
+ if(this.update.firstChild && this.update.down().childNodes) {
+ this.entryCount =
+ this.update.down().childNodes.length;
+ for (var i = 0; i < this.entryCount; i++) {
+ var entry = this.getEntry(i);
+ entry.autocompleteIndex = i;
+ this.addObservers(entry);
+ }
+ } else {
+ this.entryCount = 0;
+ }
+
+ this.stopIndicator();
+ this.index = 0;
+
+ if(this.entryCount==1 && this.options.autoSelect) {
+ this.selectEntry();
+ this.hide();
+ } else {
+ this.render();
+ }
+ }
+ },
+
+ addObservers: function(element) {
+ Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
+ Event.observe(element, "click", this.onClick.bindAsEventListener(this));
+ },
+
+ onObserverEvent: function() {
+ this.changed = false;
+ this.tokenBounds = null;
+ if(this.getToken().length>=this.options.minChars) {
+ this.getUpdatedChoices();
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ this.oldElementValue = this.element.value;
+ },
+
+ getToken: function() {
+ var bounds = this.getTokenBounds();
+ return this.element.value.substring(bounds[0], bounds[1]).strip();
+ },
+
+ getTokenBounds: function() {
+ if (null != this.tokenBounds) return this.tokenBounds;
+ var value = this.element.value;
+ if (value.strip().empty()) return [-1, 0];
+ var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
+ var offset = (diff == this.oldElementValue.length ? 1 : 0);
+ var prevTokenPos = -1, nextTokenPos = value.length;
+ var tp;
+ for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
+ tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
+ if (tp > prevTokenPos) prevTokenPos = tp;
+ tp = value.indexOf(this.options.tokens[index], diff + offset);
+ if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
+ }
+ return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
+ }
+});
+
+Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
+ var boundary = Math.min(newS.length, oldS.length);
+ for (var index = 0; index < boundary; ++index)
+ if (newS[index] != oldS[index])
+ return index;
+ return boundary;
+};
+
+Ajax.Autocompleter = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, url, options) {
+ this.baseInitialize(element, update, options);
+ this.options.asynchronous = true;
+ this.options.onComplete = this.onComplete.bind(this);
+ this.options.defaultParams = this.options.parameters || null;
+ this.url = url;
+ },
+
+ getUpdatedChoices: function() {
+ this.startIndicator();
+
+ var entry = encodeURIComponent(this.options.paramName) + '=' +
+ encodeURIComponent(this.getToken());
+
+ this.options.parameters = this.options.callback ?
+ this.options.callback(this.element, entry) : entry;
+
+ if(this.options.defaultParams)
+ this.options.parameters += '&' + this.options.defaultParams;
+
+ new Ajax.Request(this.url, this.options);
+ },
+
+ onComplete: function(request) {
+ this.updateChoices(request.responseText);
+ }
+});
+
+// The local array autocompleter. Used when you'd prefer to
+// inject an array of autocompletion options into the page, rather
+// than sending out Ajax queries, which can be quite slow sometimes.
+//
+// The constructor takes four parameters. The first two are, as usual,
+// the id of the monitored textbox, and id of the autocompletion menu.
+// The third is the array you want to autocomplete from, and the fourth
+// is the options block.
+//
+// Extra local autocompletion options:
+// - choices - How many autocompletion choices to offer
+//
+// - partialSearch - If false, the autocompleter will match entered
+// text only at the beginning of strings in the
+// autocomplete array. Defaults to true, which will
+// match text at the beginning of any *word* in the
+// strings in the autocomplete array. If you want to
+// search anywhere in the string, additionally set
+// the option fullSearch to true (default: off).
+//
+// - fullSsearch - Search anywhere in autocomplete array strings.
+//
+// - partialChars - How many characters to enter before triggering
+// a partial match (unlike minChars, which defines
+// how many characters are required to do any match
+// at all). Defaults to 2.
+//
+// - ignoreCase - Whether to ignore case when autocompleting.
+// Defaults to true.
+//
+// It's possible to pass in a custom function as the 'selector'
+// option, if you prefer to write your own autocompletion logic.
+// In that case, the other options above will not apply unless
+// you support them.
+
+Autocompleter.Local = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, array, options) {
+ this.baseInitialize(element, update, options);
+ this.options.array = array;
+ },
+
+ getUpdatedChoices: function() {
+ this.updateChoices(this.options.selector(this));
+ },
+
+ setOptions: function(options) {
+ this.options = Object.extend({
+ choices: 10,
+ partialSearch: true,
+ partialChars: 2,
+ ignoreCase: true,
+ fullSearch: false,
+ selector: function(instance) {
+ var ret = []; // Beginning matches
+ var partial = []; // Inside matches
+ var entry = instance.getToken();
+ var count = 0;
+
+ for (var i = 0; i < instance.options.array.length &&
+ ret.length < instance.options.choices ; i++) {
+
+ var elem = instance.options.array[i];
+ var foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase()) :
+ elem.indexOf(entry);
+
+ while (foundPos != -1) {
+ if (foundPos == 0 && elem.length != entry.length) {
+ ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
+ elem.substr(entry.length) + "</li>");
+ break;
+ } else if (entry.length >= instance.options.partialChars &&
+ instance.options.partialSearch && foundPos != -1) {
+ if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
+ partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
+ elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
+ foundPos + entry.length) + "</li>");
+ break;
+ }
+ }
+
+ foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
+ elem.indexOf(entry, foundPos + 1);
+
+ }
+ }
+ if (partial.length)
+ ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
+ return "<ul>" + ret.join('') + "</ul>";
+ }
+ }, options || { });
+ }
+});
+
+// AJAX in-place editor and collection editor
+// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
+
+// Use this if you notice weird scrolling problems on some browsers,
+// the DOM might be a bit confused when this gets called so do this
+// waits 1 ms (with setTimeout) until it does the activation
+Field.scrollFreeActivate = function(field) {
+ setTimeout(function() {
+ Field.activate(field);
+ }, 1);
+};
+
+Ajax.InPlaceEditor = Class.create({
+ initialize: function(element, url, options) {
+ this.url = url;
+ this.element = element = $(element);
+ this.prepareOptions();
+ this._controls = { };
+ arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
+ Object.extend(this.options, options || { });
+ if (!this.options.formId && this.element.id) {
+ this.options.formId = this.element.id + '-inplaceeditor';
+ if ($(this.options.formId))
+ this.options.formId = '';
+ }
+ if (this.options.externalControl)
+ this.options.externalControl = $(this.options.externalControl);
+ if (!this.options.externalControl)
+ this.options.externalControlOnly = false;
+ this._originalBackground = this.element.getStyle('background-color') || 'transparent';
+ this.element.title = this.options.clickToEditText;
+ this._boundCancelHandler = this.handleFormCancellation.bind(this);
+ this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
+ this._boundFailureHandler = this.handleAJAXFailure.bind(this);
+ this._boundSubmitHandler = this.handleFormSubmission.bind(this);
+ this._boundWrapperHandler = this.wrapUp.bind(this);
+ this.registerListeners();
+ },
+ checkForEscapeOrReturn: function(e) {
+ if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
+ if (Event.KEY_ESC == e.keyCode)
+ this.handleFormCancellation(e);
+ else if (Event.KEY_RETURN == e.keyCode)
+ this.handleFormSubmission(e);
+ },
+ createControl: function(mode, handler, extraClasses) {
+ var control = this.options[mode + 'Control'];
+ var text = this.options[mode + 'Text'];
+ if ('button' == control) {
+ var btn = document.createElement('input');
+ btn.type = 'submit';
+ btn.value = text;
+ btn.className = 'editor_' + mode + '_button';
+ if ('cancel' == mode)
+ btn.onclick = this._boundCancelHandler;
+ this._form.appendChild(btn);
+ this._controls[mode] = btn;
+ } else if ('link' == control) {
+ var link = document.createElement('a');
+ link.href = '#';
+ link.appendChild(document.createTextNode(text));
+ link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
+ link.className = 'editor_' + mode + '_link';
+ if (extraClasses)
+ link.className += ' ' + extraClasses;
+ this._form.appendChild(link);
+ this._controls[mode] = link;
+ }
+ },
+ createEditField: function() {
+ var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
+ var fld;
+ if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
+ fld = document.createElement('input');
+ fld.type = 'text';
+ var size = this.options.size || this.options.cols || 0;
+ if (0 < size) fld.size = size;
+ } else {
+ fld = document.createElement('textarea');
+ fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
+ fld.cols = this.options.cols || 40;
+ }
+ fld.name = this.options.paramName;
+ fld.value = text; // No HTML breaks conversion anymore
+ fld.className = 'editor_field';
+ if (this.options.submitOnBlur)
+ fld.onblur = this._boundSubmitHandler;
+ this._controls.editor = fld;
+ if (this.options.loadTextURL)
+ this.loadExternalText();
+ this._form.appendChild(this._controls.editor);
+ },
+ createForm: function() {
+ var ipe = this;
+ function addText(mode, condition) {
+ var text = ipe.options['text' + mode + 'Controls'];
+ if (!text || condition === false) return;
+ ipe._form.appendChild(document.createTextNode(text));
+ };
+ this._form = $(document.createElement('form'));
+ this._form.id = this.options.formId;
+ this._form.addClassName(this.options.formClassName);
+ this._form.onsubmit = this._boundSubmitHandler;
+ this.createEditField();
+ if ('textarea' == this._controls.editor.tagName.toLowerCase())
+ this._form.appendChild(document.createElement('br'));
+ if (this.options.onFormCustomization)
+ this.options.onFormCustomization(this, this._form);
+ addText('Before', this.options.okControl || this.options.cancelControl);
+ this.createControl('ok', this._boundSubmitHandler);
+ addText('Between', this.options.okControl && this.options.cancelControl);
+ this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');