Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

adding episode 117

  • Loading branch information...
commit 9ed7ed4c27bc72dea51c4f5f53641fb2b239074e 1 parent 52c9fd5
@ryanb authored
Showing with 8,683 additions and 0 deletions.
  1. +7 −0 episode-117/README
  2. +3 −0  episode-117/store/.gitignore
  3. +4 −0 episode-117/store/README
  4. +10 −0 episode-117/store/Rakefile
  5. +15 −0 episode-117/store/app/controllers/application.rb
  6. +44 −0 episode-117/store/app/controllers/categories_controller.rb
  7. +10 −0 episode-117/store/app/controllers/info_controller.rb
  8. +49 −0 episode-117/store/app/controllers/pages_controller.rb
  9. +44 −0 episode-117/store/app/controllers/products_controller.rb
  10. +3 −0  episode-117/store/app/helpers/application_helper.rb
  11. +2 −0  episode-117/store/app/helpers/categories_helper.rb
  12. +2 −0  episode-117/store/app/helpers/info_helper.rb
  13. +23 −0 episode-117/store/app/helpers/layout_helper.rb
  14. +3 −0  episode-117/store/app/helpers/pages_helper.rb
  15. +2 −0  episode-117/store/app/helpers/products_helper.rb
  16. +3 −0  episode-117/store/app/models/category.rb
  17. +3 −0  episode-117/store/app/models/page.rb
  18. +3 −0  episode-117/store/app/models/product.rb
  19. +7 −0 episode-117/store/app/views/categories/_form.html.erb
  20. +8 −0 episode-117/store/app/views/categories/edit.html.erb
  21. +13 −0 episode-117/store/app/views/categories/index.html.erb
  22. +5 −0 episode-117/store/app/views/categories/new.html.erb
  23. +13 −0 episode-117/store/app/views/categories/show.html.erb
  24. +9 −0 episode-117/store/app/views/info/about.html.erb
  25. +11 −0 episode-117/store/app/views/info/contact.html.erb
  26. +11 −0 episode-117/store/app/views/info/license.html.erb
  27. +11 −0 episode-117/store/app/views/info/privacy.html.erb
  28. +22 −0 episode-117/store/app/views/layouts/application.html.erb
  29. +15 −0 episode-117/store/app/views/pages/_form.html.erb
  30. +8 −0 episode-117/store/app/views/pages/edit.html.erb
  31. +21 −0 episode-117/store/app/views/pages/index.html.erb
  32. +5 −0 episode-117/store/app/views/pages/new.html.erb
  33. +9 −0 episode-117/store/app/views/pages/show.html.erb
  34. +19 −0 episode-117/store/app/views/products/_form.html.erb
  35. +8 −0 episode-117/store/app/views/products/edit.html.erb
  36. +16 −0 episode-117/store/app/views/products/index.html.erb
  37. +5 −0 episode-117/store/app/views/products/new.html.erb
  38. +21 −0 episode-117/store/app/views/products/show.html.erb
  39. +109 −0 episode-117/store/config/boot.rb
  40. +19 −0 episode-117/store/config/database.yml
  41. +69 −0 episode-117/store/config/environment.rb
  42. +17 −0 episode-117/store/config/environments/development.rb
  43. +22 −0 episode-117/store/config/environments/production.rb
  44. +22 −0 episode-117/store/config/environments/test.rb
  45. +10 −0 episode-117/store/config/initializers/inflections.rb
  46. +5 −0 episode-117/store/config/initializers/mime_types.rb
  47. +15 −0 episode-117/store/config/initializers/new_rails_defaults.rb
  48. +16 −0 episode-117/store/config/routes.rb
  49. +12 −0 episode-117/store/db/migrate/20080621194238_create_categories.rb
  50. +15 −0 episode-117/store/db/migrate/20080621194423_create_products.rb
  51. +14 −0 episode-117/store/db/migrate/20080707044755_create_pages.rb
  52. +37 −0 episode-117/store/db/schema.rb
  53. +22 −0 episode-117/store/lib/tasks/application.rake
  54. +30 −0 episode-117/store/public/404.html
  55. +30 −0 episode-117/store/public/422.html
  56. +30 −0 episode-117/store/public/500.html
  57. +10 −0 episode-117/store/public/dispatch.cgi
  58. +24 −0 episode-117/store/public/dispatch.fcgi
  59. +10 −0 episode-117/store/public/dispatch.rb
  60. 0  episode-117/store/public/favicon.ico
  61. +2 −0  episode-117/store/public/javascripts/application.js
  62. +963 −0 episode-117/store/public/javascripts/controls.js
  63. +972 −0 episode-117/store/public/javascripts/dragdrop.js
  64. +1,120 −0 episode-117/store/public/javascripts/effects.js
  65. +4,225 −0 episode-117/store/public/javascripts/prototype.js
  66. +5 −0 episode-117/store/public/robots.txt
  67. +92 −0 episode-117/store/public/stylesheets/application.css
  68. +3 −0  episode-117/store/script/about
  69. +3 −0  episode-117/store/script/console
  70. +3 −0  episode-117/store/script/dbconsole
  71. +3 −0  episode-117/store/script/destroy
  72. +3 −0  episode-117/store/script/generate
  73. +3 −0  episode-117/store/script/performance/benchmarker
  74. +3 −0  episode-117/store/script/performance/profiler
  75. +3 −0  episode-117/store/script/performance/request
  76. +3 −0  episode-117/store/script/plugin
  77. +3 −0  episode-117/store/script/process/inspector
  78. +3 −0  episode-117/store/script/process/reaper
  79. +3 −0  episode-117/store/script/process/spawner
  80. +3 −0  episode-117/store/script/runner
  81. +3 −0  episode-117/store/script/server
  82. +5 −0 episode-117/store/test/fixtures/categories.yml
  83. +9 −0 episode-117/store/test/fixtures/pages.yml
  84. +11 −0 episode-117/store/test/fixtures/products.yml
  85. +54 −0 episode-117/store/test/functional/categories_controller_test.rb
  86. +8 −0 episode-117/store/test/functional/info_controller_test.rb
  87. +54 −0 episode-117/store/test/functional/pages_controller_test.rb
  88. +54 −0 episode-117/store/test/functional/products_controller_test.rb
  89. +38 −0 episode-117/store/test/test_helper.rb
  90. +8 −0 episode-117/store/test/unit/category_test.rb
  91. +8 −0 episode-117/store/test/unit/page_test.rb
  92. +8 −0 episode-117/store/test/unit/product_test.rb
  93. 0  episode-117/store/vendor/plugins/.gitignore
View
7 episode-117/README
@@ -0,0 +1,7 @@
+Railscasts Episode #117: Semi-Static Pages
+
+http://railscasts.com/episodes/117
+
+Commands
+
+ sudo gem install RedCloth --source=http://code.whytheluckystiff.net
View
3  episode-117/store/.gitignore
@@ -0,0 +1,3 @@
+tmp/*
+log/*
+*.sqlite3
View
4 episode-117/store/README
@@ -0,0 +1,4 @@
+Railscasts Example Store App
+--
+
+To setup the app, just run `rake setup`.
View
10 episode-117/store/Rakefile
@@ -0,0 +1,10 @@
+# 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.join(File.dirname(__FILE__), 'config', 'boot'))
+
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+require 'tasks/rails'
View
15 episode-117/store/app/controllers/application.rb
@@ -0,0 +1,15 @@
+# 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 => '526292d4095d0fd8135a9aa118f5956e'
+
+ # 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
View
44 episode-117/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
10 episode-117/store/app/controllers/info_controller.rb
@@ -0,0 +1,10 @@
+class InfoController < ApplicationController
+ def about
+ end
+
+ def contact
+ end
+
+ def privacy
+ end
+end
View
49 episode-117/store/app/controllers/pages_controller.rb
@@ -0,0 +1,49 @@
+class PagesController < ApplicationController
+ def index
+ @pages = Page.find(:all)
+ end
+
+ def show
+ if params[:permalink]
+ @page = Page.find_by_permalink(params[:permalink])
+ raise ActiveRecord::RecordNotFound, "Page not found" if @page.nil?
+ else
+ @page = Page.find(params[:id])
+ end
+ end
+
+ def new
+ @page = Page.new
+ end
+
+ def create
+ @page = Page.new(params[:page])
+ if @page.save
+ flash[:notice] = "Successfully created page."
+ redirect_to @page
+ else
+ render :action => 'new'
+ end
+ end
+
+ def edit
+ @page = Page.find(params[:id])
+ end
+
+ def update
+ @page = Page.find(params[:id])
+ if @page.update_attributes(params[:page])
+ flash[:notice] = "Successfully updated page."
+ redirect_to @page
+ else
+ render :action => 'edit'
+ end
+ end
+
+ def destroy
+ @page = Page.find(params[:id])
+ @page.destroy
+ flash[:notice] = "Successfully destroyed page."
+ redirect_to pages_path
+ end
+end
View
44 episode-117/store/app/controllers/products_controller.rb
@@ -0,0 +1,44 @@
+class ProductsController < ApplicationController
+ def index
+ @products = Product.all(:limit => 10)
+ 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
3  episode-117/store/app/helpers/application_helper.rb
@@ -0,0 +1,3 @@
+# Methods added to this helper will be available to all templates in the application.
+module ApplicationHelper
+end
View
2  episode-117/store/app/helpers/categories_helper.rb
@@ -0,0 +1,2 @@
+module CategoriesHelper
+end
View
2  episode-117/store/app/helpers/info_helper.rb
@@ -0,0 +1,2 @@
+module InfoHelper
+end
View
23 episode-117/store/app/helpers/layout_helper.rb
@@ -0,0 +1,23 @@
+# 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.map(&:to_s)) }
+ end
+
+ def javascript(*args)
+ args = args.map { |arg| arg == :defaults ? arg : arg.to_s }
+ content_for(:head) { javascript_include_tag(*args) }
+ end
+end
View
3  episode-117/store/app/helpers/pages_helper.rb
@@ -0,0 +1,3 @@
+module PagesHelper
+
+end
View
2  episode-117/store/app/helpers/products_helper.rb
@@ -0,0 +1,2 @@
+module ProductsHelper
+end
View
3  episode-117/store/app/models/category.rb
@@ -0,0 +1,3 @@
+class Category < ActiveRecord::Base
+ has_many :products
+end
View
3  episode-117/store/app/models/page.rb
@@ -0,0 +1,3 @@
+class Page < ActiveRecord::Base
+
+end
View
3  episode-117/store/app/models/product.rb
@@ -0,0 +1,3 @@
+class Product < ActiveRecord::Base
+ belongs_to :category
+end
View
7 episode-117/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-117/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-117/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-117/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-117/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
9 episode-117/store/app/views/info/about.html.erb
@@ -0,0 +1,9 @@
+<% title "About Us" %>
+
+<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.</p>
+
+<p>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>Aenean sapien purus, porttitor non, vulputate eget, consequatsed, lorem. Sed molestie mauris eget libero. Integer aliquam magna sed dolor.Integer sem felis, egestas at, tempor quis, tincidunt at, velit. Cras neque. Quisque sed augue.</p>
+
+<p>Sed consectetuer posuere turpis. Aliquam erat volutpat. Prointellus. Sed eget metus. Donec sapien justo, varius at, adipiscing quis, euismodsed, orci. Quisque vel pede non dui adipiscing ullamcorper. Nulla facilisi. Fusce sapien.</p>
View
11 episode-117/store/app/views/info/contact.html.erb
@@ -0,0 +1,11 @@
+<% title "Contact Information" %>
+
+<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce ut lorem id arcufaucibus porta. Integer imperdiet nunc ut dui. Nam a purus. Ut scelerisqueporttitor velit. Aenean sapien purus, porttitor non, vulputate eget, consequatsed, lorem. Sed molestie mauris eget libero. Integer aliquam magna sed dolor.Integer sem felis, egestas at, tempor quis, tincidunt at, velit. Cras neque.Quisque sed augue. Sed consectetuer posuere turpis. Aliquam erat volutpat. Prointellus. Sed eget metus. Donec sapien justo, varius at, adipiscing quis, euismodsed, orci. Quisque vel pede non dui adipiscing ullamcorper. Nulla facilisi.Fusce sapien.</p>
+
+<p>Ut nisi leo, vestibulum nec, fringilla vitae, feugiat at, lectus. Donecfringilla pretium orci. Fusce pharetra facilisis odio. Donec eget elit. Nullaeget libero ac lectus mollis feugiat. Phasellus tincidunt orci at elit. Maecenasnon ipsum. Sed fringilla. Donec ac pede. Class aptent taciti sociosqu ad litoratorquent per conubia nostra, per inceptos hymenaeos. Phasellus ac nibh.Pellentesque non dolor.</p>
+
+<p>Nullam est. Suspendisse faucibus, urna in auctor mollis, eros libero laciniametus, ut pharetra eros augue eu ligula. Nulla aliquam. Sed vitae leo. Sed acante. Quisque auctor feugiat leo. Nullam placerat nunc ut erat. Fusce orcilacus, vulputate ut, tincidunt eu, rhoncus ac, lorem. Phasellus non diam.Pellentesque eu risus.</p>
+
+<p>Nam at magna a mi lacinia scelerisque. Vestibulum erat massa, venenatis at,facilisis vel, gravida et, orci. Integer blandit ultricies ligula. Morbipellentesque euismod nisl. Aliquam quis tortor tristique purus temporpellentesque. Sed tincidunt dapibus sem. Pellentesque lorem dolor, molestie ac,elementum sed, consequat eget, mi. Sed malesuada aliquam dolor. Vestibulumsapien. Quisque ut erat. Quisque in augue. Pellentesque rutrum pharetra pede.</p>
+
+<p>Sed cursus, nunc vitae pellentesque luctus, leo ligula convallis turpis, necposuere lorem purus eget justo. Aliquam rutrum consectetuer odio. Duis vitaerisus. Quisque tellus magna, tempus semper, luctus sed, varius ut, massa. Nullamnonummy arcu et enim. Suspendisse egestas. In dui metus, bibendum a, tempusquis, suscipit tempor, erat. Proin adipiscing consectetuer justo. Maurisvulputate lacinia magna. Maecenas sit amet justo. Cras porttitor, mi necvolutpat malesuada, justo massa interdum libero, non sollicitudin enim ligulanec dolor. Vivamus et lectus. Praesent non pede. Proin at ligula et ipsumfaucibus condimentum. Fusce ullamcorper tincidunt ipsum. Proin facilisis dui etdolor. Quisque quis magna. Praesent et lacus.</p>
View
11 episode-117/store/app/views/info/license.html.erb
@@ -0,0 +1,11 @@
+<% title "License Agreement" %>
+
+<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce ut lorem id arcufaucibus porta. Integer imperdiet nunc ut dui. Nam a purus. Ut scelerisqueporttitor velit. Aenean sapien purus, porttitor non, vulputate eget, consequatsed, lorem. Sed molestie mauris eget libero. Integer aliquam magna sed dolor.Integer sem felis, egestas at, tempor quis, tincidunt at, velit. Cras neque.Quisque sed augue. Sed consectetuer posuere turpis. Aliquam erat volutpat. Prointellus. Sed eget metus. Donec sapien justo, varius at, adipiscing quis, euismodsed, orci. Quisque vel pede non dui adipiscing ullamcorper. Nulla facilisi.Fusce sapien.</p>
+
+<p>Ut nisi leo, vestibulum nec, fringilla vitae, feugiat at, lectus. Donecfringilla pretium orci. Fusce pharetra facilisis odio. Donec eget elit. Nullaeget libero ac lectus mollis feugiat. Phasellus tincidunt orci at elit. Maecenasnon ipsum. Sed fringilla. Donec ac pede. Class aptent taciti sociosqu ad litoratorquent per conubia nostra, per inceptos hymenaeos. Phasellus ac nibh.Pellentesque non dolor.</p>
+
+<p>Nullam est. Suspendisse faucibus, urna in auctor mollis, eros libero laciniametus, ut pharetra eros augue eu ligula. Nulla aliquam. Sed vitae leo. Sed acante. Quisque auctor feugiat leo. Nullam placerat nunc ut erat. Fusce orcilacus, vulputate ut, tincidunt eu, rhoncus ac, lorem. Phasellus non diam.Pellentesque eu risus.</p>
+
+<p>Nam at magna a mi lacinia scelerisque. Vestibulum erat massa, venenatis at,facilisis vel, gravida et, orci. Integer blandit ultricies ligula. Morbipellentesque euismod nisl. Aliquam quis tortor tristique purus temporpellentesque. Sed tincidunt dapibus sem. Pellentesque lorem dolor, molestie ac,elementum sed, consequat eget, mi. Sed malesuada aliquam dolor. Vestibulumsapien. Quisque ut erat. Quisque in augue. Pellentesque rutrum pharetra pede.</p>
+
+<p>Sed cursus, nunc vitae pellentesque luctus, leo ligula convallis turpis, necposuere lorem purus eget justo. Aliquam rutrum consectetuer odio. Duis vitaerisus. Quisque tellus magna, tempus semper, luctus sed, varius ut, massa. Nullamnonummy arcu et enim. Suspendisse egestas. In dui metus, bibendum a, tempusquis, suscipit tempor, erat. Proin adipiscing consectetuer justo. Maurisvulputate lacinia magna. Maecenas sit amet justo. Cras porttitor, mi necvolutpat malesuada, justo massa interdum libero, non sollicitudin enim ligulanec dolor. Vivamus et lectus. Praesent non pede. Proin at ligula et ipsumfaucibus condimentum. Fusce ullamcorper tincidunt ipsum. Proin facilisis dui etdolor. Quisque quis magna. Praesent et lacus.</p>
View
11 episode-117/store/app/views/info/privacy.html.erb
@@ -0,0 +1,11 @@
+<% title "Privacy Policy" %>
+
+<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce ut lorem id arcufaucibus porta. Integer imperdiet nunc ut dui. Nam a purus. Ut scelerisqueporttitor velit. Aenean sapien purus, porttitor non, vulputate eget, consequatsed, lorem. Sed molestie mauris eget libero. Integer aliquam magna sed dolor.Integer sem felis, egestas at, tempor quis, tincidunt at, velit. Cras neque.Quisque sed augue. Sed consectetuer posuere turpis. Aliquam erat volutpat. Prointellus. Sed eget metus. Donec sapien justo, varius at, adipiscing quis, euismodsed, orci. Quisque vel pede non dui adipiscing ullamcorper. Nulla facilisi.Fusce sapien.</p>
+
+<p>Ut nisi leo, vestibulum nec, fringilla vitae, feugiat at, lectus. Donecfringilla pretium orci. Fusce pharetra facilisis odio. Donec eget elit. Nullaeget libero ac lectus mollis feugiat. Phasellus tincidunt orci at elit. Maecenasnon ipsum. Sed fringilla. Donec ac pede. Class aptent taciti sociosqu ad litoratorquent per conubia nostra, per inceptos hymenaeos. Phasellus ac nibh.Pellentesque non dolor.</p>
+
+<p>Nullam est. Suspendisse faucibus, urna in auctor mollis, eros libero laciniametus, ut pharetra eros augue eu ligula. Nulla aliquam. Sed vitae leo. Sed acante. Quisque auctor feugiat leo. Nullam placerat nunc ut erat. Fusce orcilacus, vulputate ut, tincidunt eu, rhoncus ac, lorem. Phasellus non diam.Pellentesque eu risus.</p>
+
+<p>Nam at magna a mi lacinia scelerisque. Vestibulum erat massa, venenatis at,facilisis vel, gravida et, orci. Integer blandit ultricies ligula. Morbipellentesque euismod nisl. Aliquam quis tortor tristique purus temporpellentesque. Sed tincidunt dapibus sem. Pellentesque lorem dolor, molestie ac,elementum sed, consequat eget, mi. Sed malesuada aliquam dolor. Vestibulumsapien. Quisque ut erat. Quisque in augue. Pellentesque rutrum pharetra pede.</p>
+
+<p>Sed cursus, nunc vitae pellentesque luctus, leo ligula convallis turpis, necposuere lorem purus eget justo. Aliquam rutrum consectetuer odio. Duis vitaerisus. Quisque tellus magna, tempus semper, luctus sed, varius ut, massa. Nullamnonummy arcu et enim. Suspendisse egestas. In dui metus, bibendum a, tempusquis, suscipit tempor, erat. Proin adipiscing consectetuer justo. Maurisvulputate lacinia magna. Maecenas sit amet justo. Cras porttitor, mi necvolutpat malesuada, justo massa interdum libero, non sollicitudin enim ligulanec dolor. Vivamus et lectus. Praesent non pede. Proin at ligula et ipsumfaucibus condimentum. Fusce ullamcorper tincidunt ipsum. Proin facilisis dui etdolor. Quisque quis magna. Praesent et lacus.</p>
View
22 episode-117/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' %>
+ <%= 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
15 episode-117/store/app/views/pages/_form.html.erb
@@ -0,0 +1,15 @@
+<% form_for @page do |f| %>
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.label :permalink %><br />
+ <%= f.text_field :permalink %>
+ </p>
+ <p>
+ <%= f.label :content %><br />
+ <%= f.text_area :content %>
+ </p>
+ <p><%= f.submit "Submit" %></p>
+<% end %>
View
8 episode-117/store/app/views/pages/edit.html.erb
@@ -0,0 +1,8 @@
+<% title "Edit Page" %>
+
+<%= render :partial => 'form' %>
+
+<p>
+ <%= link_to "Show", @page %> |
+ <%= link_to "View All", pages_path %>
+</p>
View
21 episode-117/store/app/views/pages/index.html.erb
@@ -0,0 +1,21 @@
+<% title "Pages" %>
+
+<table>
+ <tr>
+ <th>Name</th>
+ <th>Permalink</th>
+ <th>Content</th>
+ </tr>
+ <% for page in @pages %>
+ <tr>
+ <td><%=h page.name %></td>
+ <td><%=h page.permalink %></td>
+ <td><%=h page.content %></td>
+ <td><%= link_to "Show", page %></td>
+ <td><%= link_to "Edit", edit_page_path(page) %></td>
+ <td><%= link_to "Destroy", page, :confirm => 'Are you sure?', :method => :delete %></td>
+ </tr>
+ <% end %>
+</table>
+
+<p><%= link_to "New Page", new_page_path %></p>
View
5 episode-117/store/app/views/pages/new.html.erb
@@ -0,0 +1,5 @@
+<% title "New Page" %>
+
+<%= render :partial => 'form' %>
+
+<p><%= link_to "Back to List", pages_path %></p>
View
9 episode-117/store/app/views/pages/show.html.erb
@@ -0,0 +1,9 @@
+<% title @page.name %>
+
+<%= RedCloth.new(@page.content).to_html %>
+
+<p>
+ <%= link_to "Edit", edit_page_path(@page) %> |
+ <%= link_to "Destroy", @page, :confirm => 'Are you sure?', :method => :delete %> |
+ <%= link_to "View All", pages_path %>
+</p>
View
19 episode-117/store/app/views/products/_form.html.erb
@@ -0,0 +1,19 @@
+<% form_for @product do |f| %>
+ <p>
+ <%= f.label :category_id %><br />
+ <%= f.collection_select :category_id, Category.all, :id, :name %>
+ </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 "Submit" %></p>
+<% end %>
View
8 episode-117/store/app/views/products/edit.html.erb
@@ -0,0 +1,8 @@
+<% title "Edit Product" %>
+
+<%= render :partial => 'form' %>
+
+<p>
+ <%= link_to "Show", @product %> |
+ <%= link_to "View All", products_path %>
+</p>
View
16 episode-117/store/app/views/products/index.html.erb
@@ -0,0 +1,16 @@
+<% title "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><%= link_to "New Product", new_product_path %></p>
View
5 episode-117/store/app/views/products/new.html.erb
@@ -0,0 +1,5 @@
+<% title "New Product" %>
+
+<%= render :partial => 'form' %>
+
+<p><%= link_to "Back to List", products_path %></p>
View
21 episode-117/store/app/views/products/show.html.erb
@@ -0,0 +1,21 @@
+<% title @product.name %>
+
+<%= simple_format h(@product.description) %>
+
+<p>
+ <strong>Price:</strong>
+ <%= number_to_currency @product.price %>
+</p>
+
+<% unless @product.category.nil? %>
+<p>
+ <strong>Category:</strong>
+ <%= link_to h(@product.category.name), @product.category %>
+</p>
+<% end %>
+
+<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
109 episode-117/store/config/boot.rb
@@ -0,0 +1,109 @@
+# Don't change this file!
+# Configure your app in config/environment.rb and config/environments/*.rb
+
+RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
+
+module Rails
+ class << self
+ def boot!
+ unless booted?
+ preinitialize
+ pick_boot.run
+ end
+ end
+
+ def booted?
+ defined? Rails::Initializer
+ end
+
+ def pick_boot
+ (vendor_rails? ? VendorBoot : GemBoot).new
+ end
+
+ def vendor_rails?
+ File.exist?("#{RAILS_ROOT}/vendor/rails")
+ end
+
+ def preinitialize
+ load(preinitializer_path) if File.exist?(preinitializer_path)
+ end
+
+ def preinitializer_path
+ "#{RAILS_ROOT}/config/preinitializer.rb"
+ end
+ end
+
+ class Boot
+ def run
+ load_initializer
+ Rails::Initializer.run(:set_load_path)
+ end
+ end
+
+ class VendorBoot < Boot
+ def load_initializer
+ require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
+ Rails::Initializer.run(:install_gem_spec_stubs)
+ end
+ end
+
+ class GemBoot < Boot
+ def load_initializer
+ self.class.load_rubygems
+ load_rails_gem
+ require 'initializer'
+ end
+
+ def load_rails_gem
+ if version = self.class.gem_version
+ gem 'rails', version
+ else
+ gem 'rails'
+ end
+ rescue Gem::LoadError => load_error
+ $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
+ exit 1
+ end
+
+ class << self
+ def rubygems_version
+ Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion
+ end
+
+ def gem_version
+ if defined? RAILS_GEM_VERSION
+ RAILS_GEM_VERSION
+ elsif ENV.include?('RAILS_GEM_VERSION')
+ ENV['RAILS_GEM_VERSION']
+ else
+ parse_gem_version(read_environment_rb)
+ end
+ end
+
+ def load_rubygems
+ require 'rubygems'
+
+ unless rubygems_version >= '0.9.4'
+ $stderr.puts %(Rails requires RubyGems >= 0.9.4 (you have #{rubygems_version}). Please `gem update --system` and try again.)
+ exit 1
+ end
+
+ rescue LoadError
+ $stderr.puts %(Rails requires RubyGems >= 0.9.4. Please install RubyGems and try again: http://rubygems.rubyforge.org)
+ exit 1
+ end
+
+ def parse_gem_version(text)
+ $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
+ end
+
+ private
+ def read_environment_rb
+ File.read("#{RAILS_ROOT}/config/environment.rb")
+ end
+ end
+ end
+end
+
+# All that for this:
+Rails.boot!
View
19 episode-117/store/config/database.yml
@@ -0,0 +1,19 @@
+# SQLite version 3.x
+# gem install sqlite3-ruby (not necessary on OS X Leopard)
+development:
+ adapter: sqlite3
+ database: db/development.sqlite3
+ 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
+ timeout: 5000
+
+production:
+ adapter: sqlite3
+ database: db/production.sqlite3
+ timeout: 5000
View
69 episode-117/store/config/environment.rb
@@ -0,0 +1,69 @@
+# 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.1.0' 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.
+ # config.gem "bj"
+ # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
+ # 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. Uncomment to use default local time.
+ config.time_zone = 'UTC'
+
+ # 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 => '_store_session',
+ :secret => '114555005035015951bcae597e86871cac497fa51daad4955210c9784cdf95ab270f46a6401edbff051ed71c60180e98b8ae095d41cd2dcf1f29684462620381'
+ }
+
+ # 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
+ # config.active_record.observers = :cacher, :garbage_collector
+
+ config.gem "RedCloth", :version => ">= 3.301", :source => "http://code.whytheluckystiff.net/"
+end
View
17 episode-117/store/config/environments/development.rb
@@ -0,0 +1,17 @@
+# 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
View
22 episode-117/store/config/environments/production.rb
@@ -0,0 +1,22 @@
+# 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
+
+# Use a different logger for distributed setups
+# config.logger = SyslogLogger.new
+
+# Full error reports are disabled and caching is turned on
+config.action_controller.consider_all_requests_local = false
+config.action_controller.perform_caching = true
+config.action_view.cache_template_loading = true
+
+# Use a different cache store in production
+# config.cache_store = :mem_cache_store
+
+# 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
View
22 episode-117/store/config/environments/test.rb
@@ -0,0 +1,22 @@
+# 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.action_controller.consider_all_requests_local = true
+config.action_controller.perform_caching = 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
View
10 episode-117/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):
+# 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-117/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
15 episode-117/store/config/initializers/new_rails_defaults.rb
@@ -0,0 +1,15 @@
+# These settings change the behavior of Rails 2 apps and will be defaults
+# for Rails 3. You can remove this initializer when Rails 3 is released.
+
+# Include Active Record class name as root for JSON serialized output.
+ActiveRecord::Base.include_root_in_json = true
+
+# Store the full class name (including module namespace) in STI type column.
+ActiveRecord::Base.store_full_sti_class = true
+
+# Use ISO 8601 format for JSON serialized times and dates.
+ActiveSupport.use_standard_json_time_format = true
+
+# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
+# if you're including raw json in an HTML page.
+ActiveSupport.escape_html_entities_in_json = false
View
16 episode-117/store/config/routes.rb
@@ -0,0 +1,16 @@
+ActionController::Routing::Routes.draw do |map|
+ map.resources :pages
+ map.resources :products
+ map.resources :categories
+ map.root :products
+
+ map.static 'static/:permalink', :controller => 'pages', :action => 'show'
+
+ # or
+
+ map.with_options :controller => 'info' do |info|
+ info.about 'about', :action => 'about'
+ info.contact 'contact', :action => 'contact'
+ info.privacy 'privacy', :action => 'privacy'
+ end
+end
View
12 episode-117/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-117/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
14 episode-117/store/db/migrate/20080707044755_create_pages.rb
@@ -0,0 +1,14 @@
+class CreatePages < ActiveRecord::Migration
+ def self.up
+ create_table :pages do |t|
+ t.string :name
+ t.string :permalink
+ t.text :content
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :pages
+ end
+end
View
37 episode-117/store/db/schema.rb
@@ -0,0 +1,37 @@
+# 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 => 20080707044755) do
+
+ create_table "categories", :force => true do |t|
+ t.string "name"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "pages", :force => true do |t|
+ t.string "name"
+ t.string "permalink"
+ t.text "content"
+ 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
22 episode-117/store/lib/tasks/application.rake
@@ -0,0 +1,22 @@
+desc "Setup all for app"
+task :setup => ['db:migrate', 'load:categories', 'load:products']
+
+namespace :load do
+ desc "Load categories into database"
+ task :categories do
+ Category.delete_all
+ ['Electronics', 'Office Supplies', 'Toys', 'Clothing', 'Groceries'].each do |name|
+ Category.create!(:name => name)
+ end
+ end
+
+ desc "Load products into database"
+ task :products do
+ Product.delete_all
+ categories = Category.all
+ lorem = "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."
+ lorem.scan(/[a-z]+/i) do |name|
+ Product.create!(:name => name.titleize, :category => categories.rand, :description => lorem, :price => [4.99, 9.99, 14.99, 19.99, 29.99].rand/10.0)
+ end
+ end
+end
View
30 episode-117/store/public/404.html
@@ -0,0 +1,30 @@
+<!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>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
30 episode-117/store/public/422.html
@@ -0,0 +1,30 @@
+<!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>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
30 episode-117/store/public/500.html
@@ -0,0 +1,30 @@
+<!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>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
10 episode-117/store/public/dispatch.cgi
@@ -0,0 +1,10 @@
+#!/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
+
+require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
+
+# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
+# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
+require "dispatcher"
+
+ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
+Dispatcher.dispatch
View
24 episode-117/store/public/dispatch.fcgi
@@ -0,0 +1,24 @@
+#!/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
+#
+# You may specify the path to the FastCGI crash log (a log of unhandled
+# exceptions which forced the FastCGI instance to exit, great for debugging)
+# and the number of requests to process before running garbage collection.
+#
+# By default, the FastCGI crash log is RAILS_ROOT/log/fastcgi.crash.log
+# and the GC period is nil (turned off). A reasonable number of requests
+# could range from 10-100 depending on the memory footprint of your app.
+#
+# Example:
+# # Default log path, normal GC behavior.
+# RailsFCGIHandler.process!
+#
+# # Default log path, 50 requests between GC.
+# RailsFCGIHandler.process! nil, 50
+#
+# # Custom log path, normal GC behavior.
+# RailsFCGIHandler.process! '/var/log/myapp_fcgi_crash.log'
+#
+require File.dirname(__FILE__) + "/../config/environment"
+require 'fcgi_handler'
+
+RailsFCGIHandler.process!
View
10 episode-117/store/public/dispatch.rb
@@ -0,0 +1,10 @@
+#!/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
+
+require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
+
+# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
+# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
+require "dispatcher"
+
+ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
+Dispatcher.dispatch
View
0  episode-117/store/public/favicon.ico
No changes.
View
2  episode-117/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
963 episode-117/store/public/javascripts/controls.js
@@ -0,0 +1,963 @@
+// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2007 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');
+ addText('After', this.options.okControl || this.options.cancelControl);
+ },
+ destroy: function() {
+ if (this._oldInnerHTML)
+ this.element.innerHTML = this._oldInnerHTML;
+ this.leaveEditMode();
+ this.unregisterListeners();
+ },
+ enterEditMode: function(e) {
+ if (this._saving || this._editing) return;
+ this._editing = true;
+ this.triggerCallback('onEnterEditMode');
+ if (this.options.externalControl)
+ this.options.externalControl.hide();
+ this.element.hide();
+ this.createForm();
+ this.element.parentNode.insertBefore(this._form, this.element);
+ if (!this.options.loadTextURL)
+ this.postProcessEditField();
+ if (e) Event.stop(e);
+ },
+ enterHover: function(e) {
+ if (this.options.hoverClassName)
+ this.element.addClassName(this.options.hoverClassName);
+ if (this._saving) return;
+ this.triggerCallback('onEnterHover');
+ },
+ getText: function() {
+ return this.element.innerHTML;
+ },
+ handleAJAXFailure: function(transport) {
+ this.triggerCallback('onFailure', transport);
+ if (this._oldInnerHTML) {
+ this.element.innerHTML = this._oldInnerHTML;
+ this._oldInnerHTML = null;
+ }
+ },
+ handleFormCancellation: function(e) {
+ this.wrapUp();
+ if (e) Event.stop(e);
+ },
+ handleFormSubmission: function(e) {
+ var form = this._form;
+ var value = $F(this._controls.editor);
+ this.prepareSubmission();
+ var params = this.options.callback(form, value) || '';
+ if (Object.isString(params))
+ params = params.toQueryParams();
+ params.editorId = this.element.id;
+ if (this.options.htmlResponse) {
+ var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: params,
+ onComplete: this._boundWrapperHandler,
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Updater({ success: this.element }, this.url, options);
+ } else {
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: params,
+ onComplete: this._boundWrapperHandler,
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Request(this.url, options);
+ }
+ if (e) Event.stop(e);
+ },
+ leaveEditMode: function() {
+ this.element.removeClassName(this.options.savingClassName);
+ this.removeForm();
+ this.leaveHover();
+ this.element.style.backgroundColor = this._originalBackground;
+ this.element.show();
+ if (this.options.externalControl)
+ this.options.externalControl.show();
+ this._saving = false;
+ this._editing = false;
+ this._oldInnerHTML = null;
+ this.triggerCallback('onLeaveEditMode');
+ },
+ leaveHover: function(e) {
+ if (this.options.hoverClassName)
+ this.element.removeClassName(this.options.hoverClassName);
+ if (this._saving) return;
+ this.triggerCallback('onLeaveHover');
+ },
+ loadExternalText: function() {
+ this._form.addClassName(this.options.loadingClassName);
+ this._controls.editor.disabled = true;
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ this._form.removeClassName(this.options.loadingClassName);
+ var text = transport.responseText;
+ if (this.options.stripLoadedTextTags)
+ text = text.stripTags();
+ this._controls.editor.value = text;
+ this._controls.editor.disabled = false;
+ this.postProcessEditField();
+ }.bind(this),
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Request(this.options.loadTextURL, options);
+ },
+ postProcessEditField: function() {
+ var fpc = this.options.fieldPostCreation;
+ if (fpc)
+ $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
+ },
+ prepareOptions: function() {
+ this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
+ Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
+ [this._extraDefaultOptions].flatten().compact().each(function(defs) {
+ Object.extend(this.options, defs);
+ }.bind(this));
+ },
+ prepareSubmission: function() {
+ this._saving = true;
+ this.removeForm();
+ this.leaveHover();
+ this.showSaving();
+ },
+ registerListeners: function() {
+ this._listeners = { };
+ var listener;
+ $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
+ listener = this[pair.value].bind(this);
+ this._listeners[pair.key] = listener;
+ if (!this.options.externalControlOnly)
+ this.element.observe(pair.key, listener);
+ if (this.options.externalControl)
+ this.options.externalControl.observe(pair.key, listener);
+ }.bind(this));
+ },
+ removeForm: function() {
+ if (!this._form) return;
+ this._form.remove();
+ this._form = null;
+ this._controls = { };
+ },
+ showSaving: function() {
+ this._oldInnerHTML = this.element.innerHTML;
+ this.element.innerHTML = this.options.savingText;
+ this.element.addClassName(this.options.savingClassName);
+ this.element.style.backgroundColor = this._originalBackground;
+ this.element.show();
+ },
+ triggerCallback: function(cbName, arg) {
+ if ('function' == typeof this.options[cbName]) {
+ this.options[cbName](this, arg);
+ }
+ },
+ unregisterListeners: function() {
+ $H(this._listeners).each(function(pair) {
+ if (!this.options.externalControlOnly)
+ this.element.stopObserving(pair.key, pair.value);
+ if (this.options.externalControl)
+ this.options.externalControl.stopObserving(pair.key, pair.value);
+ }.bind(this));
+ },
+ wrapUp: function(transport) {
+ this.leaveEditMode();
+ // Can't use triggerCallback due to backward compatibility: requires
+ // binding + direct element
+ this._boundComplete(transport, this.element);
+ }
+});
+
+Object.extend(Ajax.InPlaceEditor.prototype, {
+ dispose: Ajax.InPlaceEditor.prototype.destroy
+});
+
+Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
+ initialize: function($super, element, url, options) {
+ this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
+ $super(element, url, options);
+ },
+
+ createEditField: function() {
+ var list = document.createElement('select');
+ list.name = this.options.paramName;
+ list.size = 1;
+ this._controls.editor = list;
+ this._collection = this.options.collection || [];
+ if (this.options.loadCollectionURL)
+ this.loadCollection();
+ else
+ this.checkForExternalText();
+ this._form.appendChild(this._controls.editor);
+ },
+
+ loadCollection: function() {
+ this._form.addClassName(this.options.loadingClassName);
+ this.showLoadingText(this.options.loadingCollectionText);
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ var js = transport.responseText.strip();
+ if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
+ throw 'Server returned an invalid collection representation.';
+ this._collection = eval(js);
+ this.checkForExternalText();
+ }.bind(this),
+ onFailure: this.onFailure
+ });
+ new Ajax.Request(this.options.loadCollectionURL, options);
+ },
+
+ showLoadingText: function(text) {
+ this._controls.editor.disabled = true;
+ var tempOption = this._controls.editor.firstChild;
+ if (!tempOption) {
+ tempOption = document.createElement('option');
+ tempOption.value = '';
+ this._controls.editor.appendChild(tempOption);
+ tempOption.selected = true;
+ }
+ tempOption.update((text || '').stripScripts().stripTags());
+ },
+
+ checkForExternalText: function() {
+ this._text = this.getText();
+ if (this.options.loadTextURL)
+ this.loadExternalText();
+ else
+ this.buildOptionList();
+ },
+
+ loadExternalText: function() {
+ this.showLoadingText(this.options.loadingText);
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ this._text = transport.responseText.strip();
+ this.buildOptionList();
+ }.bind(this),
+ onFailure: this.onFailure
+ });
+ new Ajax.Request(this.options.loadTextURL, options);
+ },
+
+ buildOptionList: function() {
+ this._form.removeClassName(this.options.loadingClassName);
+ this._collection = this._collection.map(function(entry) {
+ return 2 === entry.length ? entry : [entry, entry].flatten();
+ });
+ var marker = ('value' in this.options) ? this.options.value : this._text;
+ var textFound = this._collection.any(function(entry) {
+ return entry[0] == marker;
+ }.bind(this));
+ this._controls.editor.update('');
+ var option;
+ this._collection.each(function(entry, index) {
+ option = document.createElement('option');
+ option.value = entry[0];
+ option.selected = textFound ? entry[0] == marker : 0 == index;
+ option.appendChild(document.createTextNode(entry[1]));
+ this._controls.editor.appendC