Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

adding episode 116

  • Loading branch information...
commit 3f052e713adc3814792b56647d750c9c4ba3a275 1 parent 540954a
@ryanb authored
Showing with 33,497 additions and 0 deletions.
  1. +10 −0 episode-116/README
  2. +3 −0  episode-116/store/.gitignore
  3. +4 −0 episode-116/store/README
  4. +10 −0 episode-116/store/Rakefile
  5. +15 −0 episode-116/store/app/controllers/application.rb
  6. +44 −0 episode-116/store/app/controllers/categories_controller.rb
  7. +47 −0 episode-116/store/app/controllers/products_controller.rb
  8. +3 −0  episode-116/store/app/helpers/application_helper.rb
  9. +2 −0  episode-116/store/app/helpers/categories_helper.rb
  10. +23 −0 episode-116/store/app/helpers/layout_helper.rb
  11. +2 −0  episode-116/store/app/helpers/products_helper.rb
  12. +3 −0  episode-116/store/app/models/category.rb
  13. +3 −0  episode-116/store/app/models/product.rb
  14. +7 −0 episode-116/store/app/views/categories/_form.html.erb
  15. +8 −0 episode-116/store/app/views/categories/edit.html.erb
  16. +13 −0 episode-116/store/app/views/categories/index.html.erb
  17. +5 −0 episode-116/store/app/views/categories/new.html.erb
  18. +13 −0 episode-116/store/app/views/categories/show.html.erb
  19. +23 −0 episode-116/store/app/views/layouts/application.html.erb
  20. +19 −0 episode-116/store/app/views/products/_form.html.erb
  21. +3 −0  episode-116/store/app/views/products/destroy.js.rjs
  22. +8 −0 episode-116/store/app/views/products/edit.html.erb
  23. +16 −0 episode-116/store/app/views/products/index.html.erb
  24. +5 −0 episode-116/store/app/views/products/new.html.erb
  25. +21 −0 episode-116/store/app/views/products/show.html.erb
  26. +109 −0 episode-116/store/config/boot.rb
  27. +19 −0 episode-116/store/config/database.yml
  28. +67 −0 episode-116/store/config/environment.rb
  29. +17 −0 episode-116/store/config/environments/development.rb
  30. +22 −0 episode-116/store/config/environments/production.rb
  31. +22 −0 episode-116/store/config/environments/test.rb
  32. +10 −0 episode-116/store/config/initializers/inflections.rb
  33. +5 −0 episode-116/store/config/initializers/mime_types.rb
  34. +15 −0 episode-116/store/config/initializers/new_rails_defaults.rb
  35. +5 −0 episode-116/store/config/routes.rb
  36. +33 −0 episode-116/store/config/selenium.yml
  37. +12 −0 episode-116/store/db/migrate/20080621194238_create_categories.rb
  38. +15 −0 episode-116/store/db/migrate/20080621194423_create_products.rb
  39. +29 −0 episode-116/store/db/schema.rb
  40. +22 −0 episode-116/store/lib/tasks/application.rake
  41. +30 −0 episode-116/store/public/404.html
  42. +30 −0 episode-116/store/public/422.html
  43. +30 −0 episode-116/store/public/500.html
  44. +10 −0 episode-116/store/public/dispatch.cgi
  45. +24 −0 episode-116/store/public/dispatch.fcgi
  46. +10 −0 episode-116/store/public/dispatch.rb
  47. 0  episode-116/store/public/favicon.ico
  48. +2 −0  episode-116/store/public/javascripts/application.js
  49. +963 −0 episode-116/store/public/javascripts/controls.js
  50. +972 −0 episode-116/store/public/javascripts/dragdrop.js
  51. +1,120 −0 episode-116/store/public/javascripts/effects.js
  52. +4,225 −0 episode-116/store/public/javascripts/prototype.js
  53. +5 −0 episode-116/store/public/robots.txt
  54. +88 −0 episode-116/store/public/stylesheets/application.css
  55. +3 −0  episode-116/store/script/about
  56. +3 −0  episode-116/store/script/console
  57. +3 −0  episode-116/store/script/dbconsole
  58. +3 −0  episode-116/store/script/destroy
  59. +3 −0  episode-116/store/script/generate
  60. +3 −0  episode-116/store/script/performance/benchmarker
  61. +3 −0  episode-116/store/script/performance/profiler
  62. +3 −0  episode-116/store/script/performance/request
  63. +3 −0  episode-116/store/script/plugin
  64. +3 −0  episode-116/store/script/process/inspector
  65. +3 −0  episode-116/store/script/process/reaper
  66. +3 −0  episode-116/store/script/process/spawner
  67. +3 −0  episode-116/store/script/runner
  68. +3 −0  episode-116/store/script/server
  69. +5 −0 episode-116/store/test/fixtures/categories.yml
  70. +9 −0 episode-116/store/test/fixtures/products.yml
  71. +54 −0 episode-116/store/test/functional/categories_controller_test.rb
  72. +54 −0 episode-116/store/test/functional/products_controller_test.rb
  73. +9 −0 episode-116/store/test/selenium/destroy_product.rsel
  74. +38 −0 episode-116/store/test/test_helper.rb
  75. +8 −0 episode-116/store/test/unit/category_test.rb
  76. +8 −0 episode-116/store/test/unit/product_test.rb
  77. 0  episode-116/store/vendor/plugins/.gitignore
  78. +1 −0  episode-116/store/vendor/plugins/selenium-on-rails/.gitignore
  79. +125 −0 episode-116/store/vendor/plugins/selenium-on-rails/CHANGELOG
  80. +202 −0 episode-116/store/vendor/plugins/selenium-on-rails/LICENSE-2.0.txt
  81. +193 −0 episode-116/store/vendor/plugins/selenium-on-rails/README
  82. +27 −0 episode-116/store/vendor/plugins/selenium-on-rails/Rakefile
  83. +33 −0 episode-116/store/vendor/plugins/selenium-on-rails/config.yml.example
  84. +19 −0 episode-116/store/vendor/plugins/selenium-on-rails/generators/selenium/USAGE
  85. +50 −0 episode-116/store/vendor/plugins/selenium-on-rails/generators/selenium/selenium_generator.rb
  86. +16 −0 episode-116/store/vendor/plugins/selenium-on-rails/generators/selenium/templates/rhtml.rhtml
  87. +14 −0 episode-116/store/vendor/plugins/selenium-on-rails/generators/selenium/templates/rselenese.rhtml
  88. +11 −0 episode-116/store/vendor/plugins/selenium-on-rails/generators/selenium/templates/selenese.rhtml
  89. +20 −0 episode-116/store/vendor/plugins/selenium-on-rails/init.rb
  90. +119 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/controllers/selenium_controller.rb
  91. +9 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_helper.rb
  92. +11 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails.rb
  93. +213 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/acceptance_test_runner.rb
  94. +56 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/fixture_loader.rb
  95. +38 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/partials_support.rb
  96. +55 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/paths.rb
  97. +17 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/renderer.rb
  98. +39 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/rselenese.rb
  99. +86 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/selenese.rb
  100. +51 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/suite_renderer.rb
  101. +113 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/test_builder.rb
  102. +1,002 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/test_builder_accessors.rb
  103. +515 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/test_builder_actions.rb
  104. +91 −0 ...ode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/test_builder_user_accessors.rb.example
  105. +24 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails/test_builder_user_actions.rb.example
  106. +25 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/selenium_on_rails_config.rb
  107. +18 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/views/layout.rhtml
  108. +5 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/views/record.rhtml
  109. +67 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/views/setup.rhtml
  110. +26 −0 episode-116/store/vendor/plugins/selenium-on-rails/lib/views/test_suite.rhtml
  111. +23 −0 episode-116/store/vendor/plugins/selenium-on-rails/routes.rb
  112. +8 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/Blank.html
  113. +8 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/InjectedRemoteRunner.html
  114. +109 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/RemoteRunner.html
  115. +74 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/SeleniumLog.html
  116. +123 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/TestPrompt.html
  117. +55 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/TestRunner-splash.html
  118. +175 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/TestRunner.hta
  119. +175 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/TestRunner.html
  120. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/domviewer/butmin.gif
  121. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/domviewer/butplus.gif
  122. +298 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/domviewer/domviewer.css
  123. +16 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/domviewer/domviewer.html
  124. +205 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/domviewer/selenium-domviewer.js
  125. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/icons/all.png
  126. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/icons/continue.png
  127. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/icons/continue_disabled.png
  128. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/icons/pause.png
  129. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/icons/pause_disabled.png
  130. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/icons/selected.png
  131. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/icons/step.png
  132. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/icons/step_disabled.png
  133. +1,431 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/iedoc-core.xml
  134. +1,368 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/iedoc.xml
  135. +6 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/cssQuery/cssQuery-p.js
  136. +142 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/cssQuery/src/cssQuery-level2.js
  137. +150 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/cssQuery/src/cssQuery-level3.js
  138. +53 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/cssQuery/src/cssQuery-standard.js
  139. +356 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/cssQuery/src/cssQuery.js
  140. +2,006 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/prototype.js
  141. +101 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/scriptaculous/builder.js
  142. +815 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/scriptaculous/controls.js
  143. +915 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/scriptaculous/dragdrop.js
  144. +958 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/scriptaculous/effects.js
  145. +47 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/scriptaculous/scriptaculous.js
  146. +283 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/scriptaculous/slider.js
  147. +383 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/lib/scriptaculous/unittest.js
  148. +69 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/find_matching_child.js
  149. +842 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/htmlutils.js
  150. +79 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/injection.html
  151. +7 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/injection_iframe.html
  152. +70 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/js2html.js
  153. +175 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/narcissus-defs.js
  154. +1,054 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/narcissus-exec.js
  155. +1,003 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/narcissus-parse.js
  156. +63 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/se2html.js
  157. +2,329 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/selenium-api.js
  158. +1,946 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/selenium-browserbot.js
  159. +142 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/selenium-browserdetect.js
  160. +375 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/selenium-commandhandlers.js
  161. +177 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/selenium-executionloop.js
  162. +139 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/selenium-logging.js
  163. +466 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/selenium-remoterunner.js
  164. +1,281 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/selenium-testrunner.js
  165. +5 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/selenium-version.js
  166. +75 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/user-extensions.js.sample
  167. +153 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/scripts/xmlextras.js
  168. BIN  episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/selenium-logo.png
  169. +43 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/selenium-test.css
  170. +299 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/selenium.css
  171. +428 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/xpath/dom.js
  172. +255 −0 episode-116/store/vendor/plugins/selenium-on-rails/selenium-core/xpath/misc.js
Sorry, we could not display the entire diff because it was too big.
View
10 episode-116/README
@@ -0,0 +1,10 @@
+Railscasts Episode #116: Selenium
+
+http://railscasts.com/episodes/116
+
+Outline
+- start server in test env
+- show testing product creation with Selenium IDE
+- install selenium on rails plugin
+- generate selenium test case for destroy action
+- fix confirmation bug
View
3  episode-116/store/.gitignore
@@ -0,0 +1,3 @@
+tmp/*
+log/*
+*.sqlite3
View
4 episode-116/store/README
@@ -0,0 +1,4 @@
+Railscasts Example Store App
+--
+
+To setup the app, just run `rake setup`.
View
10 episode-116/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-116/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-116/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
47 episode-116/store/app/controllers/products_controller.rb
@@ -0,0 +1,47 @@
+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."
+ respond_to do |format|
+ format.html { redirect_to(products_url) }
+ format.js
+ end
+ end
+end
View
3  episode-116/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-116/store/app/helpers/categories_helper.rb
@@ -0,0 +1,2 @@
+module CategoriesHelper
+end
View
23 episode-116/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
2  episode-116/store/app/helpers/products_helper.rb
@@ -0,0 +1,2 @@
+module ProductsHelper
+end
View
3  episode-116/store/app/models/category.rb
@@ -0,0 +1,3 @@
+class Category < ActiveRecord::Base
+ has_many :products
+end
View
3  episode-116/store/app/models/product.rb
@@ -0,0 +1,3 @@
+class Product < ActiveRecord::Base
+ belongs_to :category
+end
View
7 episode-116/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-116/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-116/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-116/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-116/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
23 episode-116/store/app/views/layouts/application.html.erb
@@ -0,0 +1,23 @@
+<!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' %>
+ <%= javascript_include_tag :defaults %>
+ <%= 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
19 episode-116/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
3  episode-116/store/app/views/products/destroy.js.rjs
@@ -0,0 +1,3 @@
+page[@product].remove
+page.insert_html :top, :container, content_tag(:div, flash[:notice], :id => 'flash_notice')
+flash.discard
View
8 episode-116/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-116/store/app/views/products/index.html.erb
@@ -0,0 +1,16 @@
+<% title "Products" %>
+
+<% for product in @products %>
+ <% div_for product do %>
+ <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_remote "Destroy", :url => product, :method => :delete, :confirm => 'Are you sure?' %>
+ </div>
+ <% end %>
+<% end %>
+
+<p><%= link_to "New Product", new_product_path %></p>
View
5 episode-116/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-116/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-116/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-116/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
67 episode-116/store/config/environment.rb
@@ -0,0 +1,67 @@
+# 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
+end
View
17 episode-116/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-116/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-116/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-116/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-116/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-116/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
5 episode-116/store/config/routes.rb
@@ -0,0 +1,5 @@
+ActionController::Routing::Routes.draw do |map|
+ map.resources :products
+ map.resources :categories
+ map.root :products
+end
View
33 episode-116/store/config/selenium.yml
@@ -0,0 +1,33 @@
+# Rename this file to config.yml in order to configure the plugin
+
+#
+# General settings
+#
+
+environments:
+ - test
+# - development # Uncomment this line to enable in development environment. N.B. your development database will likely be altered/destroyed/abducted
+
+#selenium_path: 'c:\selenium' #path to selenium installation. only needed if you for some reason don't want to use the bundled version of selenium core
+
+#
+# rake test:acceptance settings
+#
+
+browsers:
+ # Windows
+ # firefox: 'c:\Program Files\Mozilla Firefox\firefox.exe'
+ # ie: 'c:\Program Files\Internet Explorer\iexplore.exe'
+
+ # Mac OS X
+ firefox: '/Applications/Firefox.app/Contents/MacOS/firefox-bin'
+ safari: '/Applications/Safari.app/Contents/MacOS/Safari'
+
+#host: 'localhost'
+#port_start: 3000
+#port_end: 3005
+#base_url_path: '/'
+#max_browser_duration: 120
+#multi_window: false
+
+#result_dir: 'c:\result' # the directory where the results will be stored after a test:acceptance run
View
12 episode-116/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-116/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
29 episode-116/store/db/schema.rb
@@ -0,0 +1,29 @@
+# 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 => 20080621194423) do
+
+ create_table "categories", :force => true do |t|
+ t.string "name"
+ 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-116/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-116/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-116/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-116/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-116/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-116/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-116/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-116/store/public/favicon.ico
No changes.
View
2  episode-116/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-116/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.appendChild(option);
+ }.bind(this));
+ this._controls.editor.disabled = false;
+ Field.scrollFreeActivate(this._controls.editor);
+ }
+});
+
+//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
+//**** This only exists for a while, in order to let ****
+//**** users adapt to the new API. Read up on the new ****
+//**** API and convert your code to it ASAP! ****
+
+Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
+ if (!options) return;
+ function fallback(name, expr) {
+ if (name in options || expr === undefined) return;
+ options[name] = expr;
+ };
+ fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
+ options.cancelLink == options.cancelButton == false ? false : undefined)));
+ fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
+ options.okLink == options.okButton == false ? false : undefined)));
+ fallback('highlightColor', options.highlightcolor);
+ fallback('highlightEndColor', options.highlightendcolor);
+};
+
+Object.extend(Ajax.InPlaceEditor, {
+ DefaultOptions: {
+ ajaxOptions: { },
+ autoRows: 3, // Use when multi-line w/ rows == 1
+ cancelControl: 'link', // 'link'|'button'|false
+ cancelText: 'cancel',
+ clickToEditText: 'Click to edit',
+ externalControl: null, // id|elt
+ externalControlOnly: false,
+ fieldPostCreation: 'activate', // 'activate'|'focus'|false
+ formClassName: 'inplaceeditor-form',
+ formId: null, // id|elt
+ highlightColor: '#ffff99',
+ highlightEndColor: '#ffffff',
+ hoverClassName: '',
+ htmlResponse: true,
+ loadingClassName: 'inplaceeditor-loading',
+ loadingText: 'Loading...',
+ okControl: 'button', // 'link'|'button'|false
+ okText: 'ok',
+ paramName: 'value',
+ rows: 1, // If 1 and multi-line, uses autoRows
+ savingClassName: 'inplaceeditor-saving',
+ savingText: 'Saving...',
+ size: 0,
+ stripLoadedTextTags: false,
+ submitOnBlur: false,
+ textAfterControls: '',
+ textBeforeControls: '',
+ textBetweenControls: ''
+ },
+ DefaultCallbacks: {
+ callback: function(form) {
+ return Form.serialize(form);
+ },
+ onComplete: function(transport, element) {
+ // For backward compatibility, this one is bound to the IPE, and passes
+ // the element directly. It was too often customized, so we don't break it.
+ new Effect.Highlight(element, {
+ startcolor: this.options.highlightColor, keepBackgroundImage: true });
+ },
+ onEnterEditMode: null,
+ onEnterHover: function(ipe) {
+ ipe.element.style.backgroundColor = ipe.options.highlightColor;
+ if (ipe._effect)
+ ipe._effect.cancel();
+ },
+ onFailure: function(transport, ipe) {
+ alert('Error communication with the server: ' + transport.responseText.stripTags());
+ },
+ onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
+ onLeaveEditMode: null,
+ onLeaveHover: function(ipe) {
+ ipe._effect = new Effect.Highlight(ipe.element, {
+ startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
+ restorecolor: ipe._originalBackground, keepBackgroundImage: true
+ });
+ }
+ },
+ Listeners: {
+ click: 'enterEditMode',
+ keydown: 'checkForEscapeOrReturn',
+ mouseover: 'enterHover',
+ mouseout: 'leaveHover'
+ }
+});
+
+Ajax.InPlaceCollectionEditor.DefaultOptions = {
+ loadingCollectionText: 'Loading options...'
+};
+
+// Delayed observer, like Form.Element.Observer,
+// but waits for delay after last key input
+// Ideal for live-search fields
+
+Form.Element.DelayedObserver = Class.create({
+ initialize: function(element, delay, callback) {
+ this.delay = delay || 0.5;
+ this.element = $(element);
+ this.callback = callback;
+ this.timer = null;
+ this.lastValue = $F(this.element);
+ Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
+ },
+ delayedListener: function(event) {
+ if(this.lastValue == $F(this.element)) return;
+ if(this.timer) clearTimeout(this.timer);
+ this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
+ this.lastValue = $F(this.element);
+ },
+ onTimerEvent: function() {
+ this.timer = null;
+ this.callback(this.element, $F(this.element));
+ }
+});
View
972 episode-116/store/public/javascripts/dragdrop.js
@@ -0,0 +1,972 @@
+// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)