Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

adding episode 178

  • Loading branch information...
commit a1e097d46ba10560ea3e4d67040514eb9dcf020b 1 parent c7bf4d5
@ryanb authored
Showing with 13,799 additions and 0 deletions.
  1. +9 −0 episode-178/README
  2. +4 −0 episode-178/todo/.gitignore
  3. +4 −0 episode-178/todo/README
  4. +10 −0 episode-178/todo/Rakefile
  5. +16 −0 episode-178/todo/app/controllers/application_controller.rb
  6. +46 −0 episode-178/todo/app/controllers/projects_controller.rb
  7. +43 −0 episode-178/todo/app/controllers/tasks_controller.rb
  8. +22 −0 episode-178/todo/app/controllers/user_sessions_controller.rb
  9. +15 −0 episode-178/todo/app/controllers/users_controller.rb
  10. +3 −0  episode-178/todo/app/helpers/application_helper.rb
  11. +23 −0 episode-178/todo/app/helpers/layout_helper.rb
  12. +2 −0  episode-178/todo/app/helpers/projects_helper.rb
  13. +2 −0  episode-178/todo/app/helpers/tasks_helper.rb
  14. +2 −0  episode-178/todo/app/helpers/user_sessions_helper.rb
  15. +2 −0  episode-178/todo/app/helpers/users_helper.rb
  16. +7 −0 episode-178/todo/app/models/project.rb
  17. +4 −0 episode-178/todo/app/models/task.rb
  18. +4 −0 episode-178/todo/app/models/user.rb
  19. +2 −0  episode-178/todo/app/models/user_session.rb
  20. +32 −0 episode-178/todo/app/views/layouts/application.html.erb
  21. +12 −0 episode-178/todo/app/views/projects/_form.html.erb
  22. +8 −0 episode-178/todo/app/views/projects/edit.html.erb
  23. +27 −0 episode-178/todo/app/views/projects/index.html.erb
  24. +5 −0 episode-178/todo/app/views/projects/new.html.erb
  25. +19 −0 episode-178/todo/app/views/projects/show.html.erb
  26. +12 −0 episode-178/todo/app/views/tasks/_form.html.erb
  27. +4 −0 episode-178/todo/app/views/tasks/edit.html.erb
  28. +4 −0 episode-178/todo/app/views/tasks/new.html.erb
  29. +16 −0 episode-178/todo/app/views/user_sessions/new.html.erb
  30. +24 −0 episode-178/todo/app/views/users/new.html.erb
  31. +110 −0 episode-178/todo/config/boot.rb
  32. +19 −0 episode-178/todo/config/database.yml
  33. +68 −0 episode-178/todo/config/environment.rb
  34. +17 −0 episode-178/todo/config/environments/development.rb
  35. +22 −0 episode-178/todo/config/environments/production.rb
  36. +22 −0 episode-178/todo/config/environments/test.rb
  37. +10 −0 episode-178/todo/config/initializers/inflections.rb
  38. +5 −0 episode-178/todo/config/initializers/mime_types.rb
  39. +15 −0 episode-178/todo/config/initializers/new_rails_defaults.rb
  40. +11 −0 episode-178/todo/config/routes.rb
  41. +12 −0 episode-178/todo/db/migrate/20080823221824_create_projects.rb
  42. +14 −0 episode-178/todo/db/migrate/20080823223136_create_tasks.rb
  43. +16 −0 episode-178/todo/db/migrate/20090906214105_create_users.rb
  44. +15 −0 episode-178/todo/db/migrate/20090906215606_add_attachments_photo_to_project.rb
  45. +9 −0 episode-178/todo/db/migrate/20090906220012_add_user_id_to_projects.rb
  46. +43 −0 episode-178/todo/db/schema.rb
  47. +2 −0  episode-178/todo/doc/README_FOR_APP
  48. +54 −0 episode-178/todo/lib/authentication.rb
  49. +22 −0 episode-178/todo/lib/tasks/application.rake
  50. 0  episode-178/todo/log/.gitignore
  51. +30 −0 episode-178/todo/public/404.html
  52. +30 −0 episode-178/todo/public/422.html
  53. +30 −0 episode-178/todo/public/500.html
  54. +10 −0 episode-178/todo/public/dispatch.cgi
  55. +24 −0 episode-178/todo/public/dispatch.fcgi
  56. +10 −0 episode-178/todo/public/dispatch.rb
  57. 0  episode-178/todo/public/favicon.ico
  58. +2 −0  episode-178/todo/public/javascripts/application.js
  59. +963 −0 episode-178/todo/public/javascripts/controls.js
  60. +973 −0 episode-178/todo/public/javascripts/dragdrop.js
  61. +1,128 −0 episode-178/todo/public/javascripts/effects.js
  62. +4,320 −0 episode-178/todo/public/javascripts/prototype.js
  63. +5 −0 episode-178/todo/public/robots.txt
  64. +89 −0 episode-178/todo/public/stylesheets/application.css
  65. +3 −0  episode-178/todo/script/about
  66. +3 −0  episode-178/todo/script/console
  67. +3 −0  episode-178/todo/script/dbconsole
  68. +3 −0  episode-178/todo/script/destroy
  69. +3 −0  episode-178/todo/script/generate
  70. +3 −0  episode-178/todo/script/performance/benchmarker
  71. +3 −0  episode-178/todo/script/performance/profiler
  72. +3 −0  episode-178/todo/script/performance/request
  73. +3 −0  episode-178/todo/script/plugin
  74. +3 −0  episode-178/todo/script/process/inspector
  75. +3 −0  episode-178/todo/script/process/reaper
  76. +3 −0  episode-178/todo/script/process/spawner
  77. +3 −0  episode-178/todo/script/runner
  78. +3 −0  episode-178/todo/script/server
  79. +5 −0 episode-178/todo/test/fixtures/projects.yml
  80. +9 −0 episode-178/todo/test/fixtures/tasks.yml
  81. +14 −0 episode-178/todo/test/fixtures/users.yml
  82. +54 −0 episode-178/todo/test/functional/projects_controller_test.rb
  83. +44 −0 episode-178/todo/test/functional/tasks_controller_test.rb
  84. +20 −0 episode-178/todo/test/functional/user_sessions_controller_test.rb
  85. +20 −0 episode-178/todo/test/functional/users_controller_test.rb
  86. +38 −0 episode-178/todo/test/test_helper.rb
  87. +7 −0 episode-178/todo/test/unit/project_test.rb
  88. +7 −0 episode-178/todo/test/unit/task_test.rb
  89. +4 −0 episode-178/todo/test/unit/user_test.rb
  90. 0  episode-178/todo/tmp/.gitignore
  91. 0  episode-178/todo/tmp/restart.txt
  92. +26 −0 episode-178/todo/vendor/plugins/paperclip/LICENSE
  93. +174 −0 episode-178/todo/vendor/plugins/paperclip/README.rdoc
  94. +99 −0 episode-178/todo/vendor/plugins/paperclip/Rakefile
  95. +6 −0 episode-178/todo/vendor/plugins/paperclip/cucumber/paperclip_steps.rb
  96. +5 −0 episode-178/todo/vendor/plugins/paperclip/generators/paperclip/USAGE
  97. +27 −0 episode-178/todo/vendor/plugins/paperclip/generators/paperclip/paperclip_generator.rb
  98. +19 −0 episode-178/todo/vendor/plugins/paperclip/generators/paperclip/templates/paperclip_migration.rb.erb
  99. +1 −0  episode-178/todo/vendor/plugins/paperclip/init.rb
  100. +352 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip.rb
  101. +414 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/attachment.rb
  102. +33 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/callback_compatability.rb
  103. +115 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/geometry.rb
  104. +108 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/interpolations.rb
  105. +58 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/iostream.rb
  106. +4 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/matchers.rb
  107. +49 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/matchers/have_attached_file_matcher.rb
  108. +66 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/matchers/validate_attachment_content_type_matcher.rb
  109. +48 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/matchers/validate_attachment_presence_matcher.rb
  110. +83 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/matchers/validate_attachment_size_matcher.rb
  111. +49 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/processor.rb
  112. +243 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/storage.rb
  113. +73 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/thumbnail.rb
  114. +48 −0 episode-178/todo/vendor/plugins/paperclip/lib/paperclip/upfile.rb
  115. +37 −0 episode-178/todo/vendor/plugins/paperclip/paperclip.gemspec
  116. +117 −0 episode-178/todo/vendor/plugins/paperclip/shoulda_macros/paperclip.rb
  117. +79 −0 episode-178/todo/vendor/plugins/paperclip/tasks/paperclip_tasks.rake
  118. +1 −0  episode-178/todo/vendor/plugins/paperclip/test/.gitignore
  119. +780 −0 episode-178/todo/vendor/plugins/paperclip/test/attachment_test.rb
  120. +4 −0 episode-178/todo/vendor/plugins/paperclip/test/database.yml
  121. BIN  episode-178/todo/vendor/plugins/paperclip/test/fixtures/12k.png
  122. BIN  episode-178/todo/vendor/plugins/paperclip/test/fixtures/50x50.png
  123. BIN  episode-178/todo/vendor/plugins/paperclip/test/fixtures/5k.png
  124. +1 −0  episode-178/todo/vendor/plugins/paperclip/test/fixtures/bad.png
  125. +4 −0 episode-178/todo/vendor/plugins/paperclip/test/fixtures/s3.yml
  126. 0  episode-178/todo/vendor/plugins/paperclip/test/fixtures/text.txt
  127. BIN  episode-178/todo/vendor/plugins/paperclip/test/fixtures/twopage.pdf
  128. +177 −0 episode-178/todo/vendor/plugins/paperclip/test/geometry_test.rb
  129. +108 −0 episode-178/todo/vendor/plugins/paperclip/test/helper.rb
  130. +483 −0 episode-178/todo/vendor/plugins/paperclip/test/integration_test.rb
  131. +124 −0 episode-178/todo/vendor/plugins/paperclip/test/interpolations_test.rb
  132. +71 −0 episode-178/todo/vendor/plugins/paperclip/test/iostream_test.rb
  133. +21 −0 episode-178/todo/vendor/plugins/paperclip/test/matchers/have_attached_file_matcher_test.rb
  134. +30 −0 episode-178/todo/vendor/plugins/paperclip/test/matchers/validate_attachment_content_type_matcher_test.rb
  135. +21 −0 episode-178/todo/vendor/plugins/paperclip/test/matchers/validate_attachment_presence_matcher_test.rb
  136. +50 −0 episode-178/todo/vendor/plugins/paperclip/test/matchers/validate_attachment_size_matcher_test.rb
  137. +327 −0 episode-178/todo/vendor/plugins/paperclip/test/paperclip_test.rb
  138. +10 −0 episode-178/todo/vendor/plugins/paperclip/test/processor_test.rb
  139. +280 −0 episode-178/todo/vendor/plugins/paperclip/test/storage_test.rb
  140. +227 −0 episode-178/todo/vendor/plugins/paperclip/test/thumbnail_test.rb
View
9 episode-178/README
@@ -0,0 +1,9 @@
+Railscasts Episode #178: 7 Security Tips
+
+http://railscasts.com/episodes/178
+
+script/console
+
+ p = Project.find(2)
+ p.update_attributes(:task_ids => [4])
+ p.tasks
View
4 episode-178/todo/.gitignore
@@ -0,0 +1,4 @@
+tmp/**/*
+log/*.log
+*.sqlite3
+public/photos/**/*
View
4 episode-178/todo/README
@@ -0,0 +1,4 @@
+Railscasts Example To Do App
+--
+
+To setup the app, just run `rake setup`.
View
10 episode-178/todo/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
16 episode-178/todo/app/controllers/application_controller.rb
@@ -0,0 +1,16 @@
+# 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
+ include Authentication
+ 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 => '9ae178eac1fbbd4062a93c8c558a12ef'
+
+ # 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
46 episode-178/todo/app/controllers/projects_controller.rb
@@ -0,0 +1,46 @@
+class ProjectsController < ApplicationController
+ before_filter :login_required
+
+ def index
+ @projects = current_user.projects.all(:conditions => ["name like ?", "%#{params[:search]}%"])
+ end
+
+ def show
+ @project = current_user.projects.find(params[:id])
+ end
+
+ def new
+ @project = current_user.projects.build
+ end
+
+ def create
+ @project = current_user.projects.build(params[:project])
+ if @project.save
+ flash[:notice] = "Successfully created project."
+ redirect_to @project
+ else
+ render :action => 'new'
+ end
+ end
+
+ def edit
+ @project = current_user.projects.find(params[:id])
+ end
+
+ def update
+ @project = current_user.projects.find(params[:id])
+ if @project.update_attributes(params[:project])
+ flash[:notice] = "Successfully updated project."
+ redirect_to @project
+ else
+ render :action => 'edit'
+ end
+ end
+
+ def destroy
+ @project = current_user.projects.find(params[:id])
+ @project.destroy
+ flash[:notice] = "Successfully destroyed project."
+ redirect_to projects_url
+ end
+end
View
43 episode-178/todo/app/controllers/tasks_controller.rb
@@ -0,0 +1,43 @@
+class TasksController < ApplicationController
+ before_filter :login_required
+
+ def new
+ @project = current_user.projects.find(params[:project_id])
+ @task = @project.tasks.build
+ end
+
+ def create
+ @project = current_user.projects.find(params[:project_id])
+ @task = @project.tasks.build(params[:task])
+ if @task.save
+ flash[:notice] = "Successfully created task."
+ redirect_to @task.project
+ else
+ render :action => 'new'
+ end
+ end
+
+ def edit
+ @project = current_user.projects.find(params[:project_id])
+ @task = @project.tasks.find(params[:id])
+ end
+
+ def update
+ @project = current_user.projects.find(params[:project_id])
+ @task = @project.tasks.find(params[:id])
+ if @task.update_attributes(params[:task])
+ flash[:notice] = "Successfully updated task."
+ redirect_to @task.project
+ else
+ render :action => 'edit'
+ end
+ end
+
+ def destroy
+ @project = current_user.projects.find(params[:project_id])
+ @task = @project.tasks.find(params[:id])
+ @task.destroy
+ flash[:notice] = "Successfully destroyed task."
+ redirect_to @task.project
+ end
+end
View
22 episode-178/todo/app/controllers/user_sessions_controller.rb
@@ -0,0 +1,22 @@
+class UserSessionsController < ApplicationController
+ def new
+ @user_session = UserSession.new
+ end
+
+ def create
+ @user_session = UserSession.new(params[:user_session])
+ if @user_session.save
+ flash[:notice] = "Logged in successfully."
+ redirect_to_target_or_default(root_url)
+ else
+ render :action => 'new'
+ end
+ end
+
+ def destroy
+ @user_session = UserSession.find
+ @user_session.destroy
+ flash[:notice] = "You have been logged out."
+ redirect_to root_url
+ end
+end
View
15 episode-178/todo/app/controllers/users_controller.rb
@@ -0,0 +1,15 @@
+class UsersController < ApplicationController
+ def new
+ @user = User.new
+ end
+
+ def create
+ @user = User.new(params[:user])
+ if @user.save
+ flash[:notice] = "Thank you for signing up! You are now logged in."
+ redirect_to root_url
+ else
+ render :action => 'new'
+ end
+ end
+end
View
3  episode-178/todo/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
23 episode-178/todo/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-178/todo/app/helpers/projects_helper.rb
@@ -0,0 +1,2 @@
+module ProjectsHelper
+end
View
2  episode-178/todo/app/helpers/tasks_helper.rb
@@ -0,0 +1,2 @@
+module TasksHelper
+end
View
2  episode-178/todo/app/helpers/user_sessions_helper.rb
@@ -0,0 +1,2 @@
+module UserSessionsHelper
+end
View
2  episode-178/todo/app/helpers/users_helper.rb
@@ -0,0 +1,2 @@
+module UsersHelper
+end
View
7 episode-178/todo/app/models/project.rb
@@ -0,0 +1,7 @@
+class Project < ActiveRecord::Base
+ belongs_to :user
+ has_many :tasks
+ has_attached_file :photo
+ attr_accessible :name, :photo
+ validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png']
+end
View
4 episode-178/todo/app/models/task.rb
@@ -0,0 +1,4 @@
+class Task < ActiveRecord::Base
+ belongs_to :project
+ attr_accessible :name, :complete
+end
View
4 episode-178/todo/app/models/user.rb
@@ -0,0 +1,4 @@
+class User < ActiveRecord::Base
+ acts_as_authentic
+ has_many :projects
+end
View
2  episode-178/todo/app/models/user_session.rb
@@ -0,0 +1,2 @@
+class UserSession < Authlogic::Session::Base
+end
View
32 episode-178/todo/app/views/layouts/application.html.erb
@@ -0,0 +1,32 @@
+<!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">
+ <div id="user_nav">
+ <% if logged_in? %>
+ Welcome <%=h current_user.username %>! Not you?
+ <%= link_to "Log out", logout_path %>
+ <% else %>
+ <%= link_to "Sign up", signup_path %> or
+ <%= link_to "log in", login_path %>.
+ <% end %>
+ </div>
+
+ <%- 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
12 episode-178/todo/app/views/projects/_form.html.erb
@@ -0,0 +1,12 @@
+<% form_for @project, :html => { :multipart => true } do |f| %>
+ <%= f.error_messages %>
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.label :photo %><br />
+ <%= f.file_field :photo %>
+ </p>
+ <p><%= f.submit "Submit" %></p>
+<% end %>
View
8 episode-178/todo/app/views/projects/edit.html.erb
@@ -0,0 +1,8 @@
+<% title "Edit Project" %>
+
+<%= render :partial => 'form' %>
+
+<p>
+ <%= link_to "Show", @project %> |
+ <%= link_to "View All", projects_path %>
+</p>
View
27 episode-178/todo/app/views/projects/index.html.erb
@@ -0,0 +1,27 @@
+<% title "Projects" %>
+
+<% form_tag projects_path, :method => 'get' do %>
+ <p>
+ <%= label_tag :search, "Search:" %>
+ <%= text_field_tag :search, params[:search] %>
+ </p>
+ <p>
+ <%= label_tag :search, "Sort:" %>
+ <%= select_tag :order, options_for_select([["Date Created", "created_at"], ["Name", "name"]], :selected => params[:order]) %>
+ </p>
+ <p>
+ <%= submit_tag "Search", :name => nil %>
+ </p>
+<% end %>
+
+<% for project in @projects %>
+<div class="project">
+ <h2><%= link_to h(project.name), project %></h2>
+ <p>
+ <%= link_to "Edit", edit_project_path(project) %> |
+ <%= link_to "Destroy", project, :confirm => 'Are you sure?', :method => :delete %>
+ </p>
+</div>
+<% end %>
+
+<p><%= link_to "New Project", new_project_path %></p>
View
5 episode-178/todo/app/views/projects/new.html.erb
@@ -0,0 +1,5 @@
+<% title "New Project" %>
+
+<%= render :partial => 'form' %>
+
+<p><%= link_to "Back to List", projects_path %></p>
View
19 episode-178/todo/app/views/projects/show.html.erb
@@ -0,0 +1,19 @@
+<% title @project.name %>
+
+<%= image_tag @project.photo.url %>
+
+<h2>Tasks</h2>
+<ul>
+ <% for task in @project.tasks %>
+ <li>
+ <%=h task.name %>
+ (<%= link_to "Edit", edit_project_task_path(@project, task) %> |
+ <%= link_to "Destroy", [@project, task], :confirm => "Are you sure?", :method => :delete %>)
+ </li>
+ <% end %>
+</ul>
+
+<p>
+ <%= link_to "New Task", new_project_task_path(@project) %> |
+ <%= link_to "View All Projects", projects_path %>
+</p>
View
12 episode-178/todo/app/views/tasks/_form.html.erb
@@ -0,0 +1,12 @@
+<% form_for [@project, @task] do |f| %>
+ <%= f.error_messages %>
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.check_box :complete %>
+ <%= f.label :complete %>
+ </p>
+ <p><%= f.submit "Submit" %></p>
+<% end %>
View
4 episode-178/todo/app/views/tasks/edit.html.erb
@@ -0,0 +1,4 @@
+<% title "Edit Task" %>
+
+<%= render :partial => 'form' %>
+
View
4 episode-178/todo/app/views/tasks/new.html.erb
@@ -0,0 +1,4 @@
+<% title "New Task" %>
+
+<%= render :partial => 'form' %>
+
View
16 episode-178/todo/app/views/user_sessions/new.html.erb
@@ -0,0 +1,16 @@
+<% title "Log in" %>
+
+<p>Don't have an account? <%= link_to "Sign up!", signup_path %></p>
+
+<% form_for @user_session do |f| %>
+ <%= f.error_messages %>
+ <p>
+ <%= f.label :username %><br />
+ <%= f.text_field :username %>
+ </p>
+ <p>
+ <%= f.label :password %><br />
+ <%= f.password_field :password %>
+ </p>
+ <p><%= f.submit "Log in" %></p>
+<% end %>
View
24 episode-178/todo/app/views/users/new.html.erb
@@ -0,0 +1,24 @@
+<% title "Sign up" %>
+
+<p>Already have an account? <%= link_to "Log in", login_path %>.</p>
+
+<% form_for @user do |f| %>
+ <%= f.error_messages %>
+ <p>
+ <%= f.label :username %><br />
+ <%= f.text_field :username %>
+ </p>
+ <p>
+ <%= f.label :email, "Email Address" %><br />
+ <%= f.text_field :email %>
+ </p>
+ <p>
+ <%= f.label :password %><br />
+ <%= f.password_field :password %>
+ </p>
+ <p>
+ <%= f.label :password_confirmation, "Confirm Password" %><br />
+ <%= f.password_field :password_confirmation %>
+ </p>
+ <p><%= f.submit "Sign up" %></p>
+<% end %>
View
110 episode-178/todo/config/boot.rb
@@ -0,0 +1,110 @@
+# 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)
+ Rails::GemDependency.add_frozen_gem_path
+ 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 rescue nil
+ 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'
+ min_version = '1.3.1'
+ unless rubygems_version >= min_version
+ $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
+ exit 1
+ end
+
+ rescue LoadError
+ $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. 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-178/todo/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
68 episode-178/todo/config/environment.rb
@@ -0,0 +1,68 @@
+# 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.3.3' 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"
+ config.gem "authlogic"
+
+ # 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 => '_todo_session',
+ :secret => '07def86ddce91088e93634568232251a0bd76dc17553c7c97f2b29b7edcde35f1326c37ffa265d1cbfd5544ba504a319193dabf880e20c5d7815a72705f6692c'
+ }
+
+ # 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-178/todo/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-178/todo/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-178/todo/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-178/todo/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-178/todo/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-178/todo/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
11 episode-178/todo/config/routes.rb
@@ -0,0 +1,11 @@
+ActionController::Routing::Routes.draw do |map|
+ map.signup 'signup', :controller => 'users', :action => 'new'
+ map.logout 'logout', :controller => 'user_sessions', :action => 'destroy'
+ map.login 'login', :controller => 'user_sessions', :action => 'new'
+ map.resources :user_sessions
+
+ map.resources :users
+
+ map.resources :projects, :has_many => :tasks
+ map.root :projects
+end
View
12 episode-178/todo/db/migrate/20080823221824_create_projects.rb
@@ -0,0 +1,12 @@
+class CreateProjects < ActiveRecord::Migration
+ def self.up
+ create_table :projects do |t|
+ t.string :name
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :projects
+ end
+end
View
14 episode-178/todo/db/migrate/20080823223136_create_tasks.rb
@@ -0,0 +1,14 @@
+class CreateTasks < ActiveRecord::Migration
+ def self.up
+ create_table :tasks do |t|
+ t.integer :project_id
+ t.string :name
+ t.boolean :complete
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :tasks
+ end
+end
View
16 episode-178/todo/db/migrate/20090906214105_create_users.rb
@@ -0,0 +1,16 @@
+class CreateUsers < ActiveRecord::Migration
+ def self.up
+ create_table :users do |t|
+ t.string :username
+ t.string :email
+ t.string :persistence_token
+ t.string :crypted_password
+ t.string :password_salt
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :users
+ end
+end
View
15 episode-178/todo/db/migrate/20090906215606_add_attachments_photo_to_project.rb
@@ -0,0 +1,15 @@
+class AddAttachmentsPhotoToProject < ActiveRecord::Migration
+ def self.up
+ add_column :projects, :photo_file_name, :string
+ add_column :projects, :photo_content_type, :string
+ add_column :projects, :photo_file_size, :integer
+ add_column :projects, :photo_updated_at, :datetime
+ end
+
+ def self.down
+ remove_column :projects, :photo_file_name
+ remove_column :projects, :photo_content_type
+ remove_column :projects, :photo_file_size
+ remove_column :projects, :photo_updated_at
+ end
+end
View
9 episode-178/todo/db/migrate/20090906220012_add_user_id_to_projects.rb
@@ -0,0 +1,9 @@
+class AddUserIdToProjects < ActiveRecord::Migration
+ def self.up
+ add_column :projects, :user_id, :integer
+ end
+
+ def self.down
+ remove_column :projects, :user_id
+ end
+end
View
43 episode-178/todo/db/schema.rb
@@ -0,0 +1,43 @@
+# 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 => 20090906220012) do
+
+ create_table "projects", :force => true do |t|
+ t.string "name"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ t.string "photo_file_name"
+ t.string "photo_content_type"
+ t.integer "photo_file_size"
+ t.datetime "photo_updated_at"
+ t.integer "user_id"
+ end
+
+ create_table "tasks", :force => true do |t|
+ t.integer "project_id"
+ t.string "name"
+ t.boolean "complete"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "users", :force => true do |t|
+ t.string "username"
+ t.string "email"
+ t.string "persistence_token"
+ t.string "crypted_password"
+ t.string "password_salt"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+end
View
2  episode-178/todo/doc/README_FOR_APP
@@ -0,0 +1,2 @@
+Use this README file to introduce your application and point to useful places in the API for learning more.
+Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
View
54 episode-178/todo/lib/authentication.rb
@@ -0,0 +1,54 @@
+# This module is included in your application controller which makes
+# several methods available to all controllers and views. Here's a
+# common example you might add to your application layout file.
+#
+# <% if logged_in? %>
+# Welcome <%=h current_user.username %>! Not you?
+# <%= link_to "Log out", logout_path %>
+# <% else %>
+# <%= link_to "Sign up", signup_path %> or
+# <%= link_to "log in", login_path %>.
+# <% end %>
+#
+# You can also restrict unregistered users from accessing a controller using
+# a before filter. For example.
+#
+# before_filter :login_required, :except => [:index, :show]
+module Authentication
+ def self.included(controller)
+ controller.send :helper_method, :current_user, :logged_in?, :redirect_to_target_or_default
+ end
+
+ def current_user_session
+ return @current_user_session if defined?(@current_user_session)
+ @current_user_session = UserSession.find
+ end
+
+ def current_user
+ return @current_user if defined?(@current_user)
+ @current_user = current_user_session && current_user_session.record
+ end
+
+ def logged_in?
+ current_user
+ end
+
+ def login_required
+ unless logged_in?
+ flash[:error] = "You must first log in or sign up before accessing this page."
+ store_target_location
+ redirect_to login_url
+ end
+ end
+
+ def redirect_to_target_or_default(default)
+ redirect_to(session[:return_to] || default)
+ session[:return_to] = nil
+ end
+
+ private
+
+ def store_target_location
+ session[:return_to] = request.request_uri
+ end
+end
View
22 episode-178/todo/lib/tasks/application.rake
@@ -0,0 +1,22 @@
+desc "Setup all for app"
+task :setup => ['db:migrate', 'load:projects', 'load:tasks']
+
+namespace :load do
+ desc "Load projects into database"
+ task :projects do
+ Project.delete_all
+ ['Yardwork', 'Housework', 'Programming'].each do |name|
+ Project.create!(:name => name)
+ end
+ end
+
+ desc "Load tasks into database"
+ task :tasks do
+ Task.delete_all
+ projects = Project.all
+ words = File.readlines("/usr/share/dict/words").sort_by { rand }
+ 35.times do
+ Task.create!(:name => words.pop.titleize, :project => projects.rand)
+ end
+ end
+end
View
0  episode-178/todo/log/.gitignore
No changes.
View
30 episode-178/todo/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-178/todo/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-178/todo/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-178/todo/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-178/todo/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-178/todo/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-178/todo/public/favicon.ico
No changes.
View
2  episode-178/todo/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-178/todo/public/javascripts/controls.js
@@ -0,0 +1,963 @@
+// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2008 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.unescapeHTML();
+ },
+ 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;
+