Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

adding episode 236

  • Loading branch information...
commit 39ec2fccb564b5556ab38133e798e4ae0dd9a1b2 1 parent edcaa5c
@ryanb authored
Showing with 11,211 additions and 0 deletions.
  1. +9 −0 episode-236/README
  2. +4 −0 episode-236/todo/.gitignore
  3. +9 −0 episode-236/todo/Gemfile
  4. +137 −0 episode-236/todo/Gemfile.lock
  5. +256 −0 episode-236/todo/README
  6. +7 −0 episode-236/todo/Rakefile
  7. +3 −0  episode-236/todo/app/controllers/application_controller.rb
  8. +35 −0 episode-236/todo/app/controllers/authentications_controller.rb
  9. +44 −0 episode-236/todo/app/controllers/projects_controller.rb
  10. +16 −0 episode-236/todo/app/controllers/registrations_controller.rb
  11. +36 −0 episode-236/todo/app/controllers/tasks_controller.rb
  12. +2 −0  episode-236/todo/app/helpers/application_helper.rb
  13. +2 −0  episode-236/todo/app/helpers/authentications_helper.rb
  14. +23 −0 episode-236/todo/app/helpers/error_messages_helper.rb
  15. +22 −0 episode-236/todo/app/helpers/layout_helper.rb
  16. +2 −0  episode-236/todo/app/helpers/projects_helper.rb
  17. +2 −0  episode-236/todo/app/helpers/registrations_helper.rb
  18. +2 −0  episode-236/todo/app/helpers/tasks_helper.rb
  19. +11 −0 episode-236/todo/app/models/authentication.rb
  20. +4 −0 episode-236/todo/app/models/project.rb
  21. +4 −0 episode-236/todo/app/models/task.rb
  22. +20 −0 episode-236/todo/app/models/user.rb
  23. +47 −0 episode-236/todo/app/views/authentications/index.html.erb
  24. +12 −0 episode-236/todo/app/views/devise/confirmations/new.html.erb
  25. +5 −0 episode-236/todo/app/views/devise/mailer/confirmation_instructions.html.erb
  26. +8 −0 episode-236/todo/app/views/devise/mailer/reset_password_instructions.html.erb
  27. +7 −0 episode-236/todo/app/views/devise/mailer/unlock_instructions.html.erb
  28. +16 −0 episode-236/todo/app/views/devise/passwords/edit.html.erb
  29. +12 −0 episode-236/todo/app/views/devise/passwords/new.html.erb
  30. +17 −0 episode-236/todo/app/views/devise/sessions/new.html.erb
  31. +19 −0 episode-236/todo/app/views/devise/shared/_links.erb
  32. +12 −0 episode-236/todo/app/views/devise/unlocks/new.html.erb
  33. +27 −0 episode-236/todo/app/views/layouts/application.html.erb
  34. +8 −0 episode-236/todo/app/views/projects/_form.html.erb
  35. +8 −0 episode-236/todo/app/views/projects/edit.html.erb
  36. +16 −0 episode-236/todo/app/views/projects/index.html.erb
  37. +5 −0 episode-236/todo/app/views/projects/new.html.erb
  38. +17 −0 episode-236/todo/app/views/projects/show.html.erb
  39. +25 −0 episode-236/todo/app/views/registrations/edit.html.erb
  40. +20 −0 episode-236/todo/app/views/registrations/new.html.erb
  41. +13 −0 episode-236/todo/app/views/tasks/_form.html.erb
  42. +4 −0 episode-236/todo/app/views/tasks/edit.html.erb
  43. +4 −0 episode-236/todo/app/views/tasks/new.html.erb
  44. +4 −0 episode-236/todo/config.ru
  45. +42 −0 episode-236/todo/config/application.rb
  46. +13 −0 episode-236/todo/config/boot.rb
  47. +22 −0 episode-236/todo/config/database.yml
  48. +5 −0 episode-236/todo/config/environment.rb
  49. +27 −0 episode-236/todo/config/environments/development.rb
  50. +49 −0 episode-236/todo/config/environments/production.rb
  51. +35 −0 episode-236/todo/config/environments/test.rb
  52. +7 −0 episode-236/todo/config/initializers/backtrace_silencers.rb
  53. +142 −0 episode-236/todo/config/initializers/devise.rb
  54. +10 −0 episode-236/todo/config/initializers/inflections.rb
  55. +5 −0 episode-236/todo/config/initializers/mime_types.rb
  56. +5 −0 episode-236/todo/config/initializers/omniauth.rb
  57. +7 −0 episode-236/todo/config/initializers/secret_token.rb
  58. +8 −0 episode-236/todo/config/initializers/session_store.rb
  59. +39 −0 episode-236/todo/config/locales/devise.en.yml
  60. +5 −0 episode-236/todo/config/locales/en.yml
  61. +8 −0 episode-236/todo/config/routes.rb
  62. +12 −0 episode-236/todo/db/migrate/20100927035419_create_projects.rb
  63. +14 −0 episode-236/todo/db/migrate/20100927035455_create_tasks.rb
  64. +26 −0 episode-236/todo/db/migrate/20100927035705_devise_create_users.rb
  65. +14 −0 episode-236/todo/db/migrate/20101011050048_create_authentications.rb
  66. +56 −0 episode-236/todo/db/schema.rb
  67. +7 −0 episode-236/todo/db/seeds.rb
  68. +2 −0  episode-236/todo/doc/README_FOR_APP
  69. 0  episode-236/todo/lib/tasks/.gitkeep
  70. +26 −0 episode-236/todo/public/404.html
  71. +26 −0 episode-236/todo/public/422.html
  72. +26 −0 episode-236/todo/public/500.html
  73. 0  episode-236/todo/public/favicon.ico
  74. BIN  episode-236/todo/public/images/facebook_64.png
  75. BIN  episode-236/todo/public/images/google_apps_64.png
  76. BIN  episode-236/todo/public/images/open_id_32.png
  77. BIN  episode-236/todo/public/images/open_id_64.png
  78. BIN  episode-236/todo/public/images/rails.png
  79. BIN  episode-236/todo/public/images/twitter_32.png
  80. BIN  episode-236/todo/public/images/twitter_64.png
  81. +2 −0  episode-236/todo/public/javascripts/application.js
  82. +965 −0 episode-236/todo/public/javascripts/controls.js
  83. +974 −0 episode-236/todo/public/javascripts/dragdrop.js
  84. +1,123 −0 episode-236/todo/public/javascripts/effects.js
  85. +6,001 −0 episode-236/todo/public/javascripts/prototype.js
  86. +175 −0 episode-236/todo/public/javascripts/rails.js
  87. +5 −0 episode-236/todo/public/robots.txt
  88. 0  episode-236/todo/public/stylesheets/.gitkeep
  89. +144 −0 episode-236/todo/public/stylesheets/application.css
  90. +6 −0 episode-236/todo/script/rails
  91. +9 −0 episode-236/todo/test/fixtures/authentications.yml
  92. +5 −0 episode-236/todo/test/fixtures/projects.yml
  93. +9 −0 episode-236/todo/test/fixtures/tasks.yml
  94. +11 −0 episode-236/todo/test/fixtures/users.yml
  95. +27 −0 episode-236/todo/test/functional/authentications_controller_test.rb
  96. +54 −0 episode-236/todo/test/functional/projects_controller_test.rb
  97. +8 −0 episode-236/todo/test/functional/registrations_controller_test.rb
  98. +44 −0 episode-236/todo/test/functional/tasks_controller_test.rb
  99. +9 −0 episode-236/todo/test/performance/browsing_test.rb
  100. +13 −0 episode-236/todo/test/test_helper.rb
  101. +7 −0 episode-236/todo/test/unit/authentication_test.rb
  102. +4 −0 episode-236/todo/test/unit/helpers/registrations_helper_test.rb
  103. +7 −0 episode-236/todo/test/unit/project_test.rb
  104. +7 −0 episode-236/todo/test/unit/task_test.rb
  105. +8 −0 episode-236/todo/test/unit/user_test.rb
  106. 0  episode-236/todo/vendor/plugins/.gitkeep
View
9 episode-236/README
@@ -0,0 +1,9 @@
+Railscasts Episode #236: OmniAuth Part 2
+
+http://railscasts.com/episodes/236
+
+Commands
+
+ bundle update
+ rails g controller registrations
+ rails g devise:views
View
4 episode-236/todo/.gitignore
@@ -0,0 +1,4 @@
+.bundle
+db/*.sqlite3
+log/*.log
+tmp/**/*
View
9 episode-236/todo/Gemfile
@@ -0,0 +1,9 @@
+source 'http://rubygems.org'
+
+gem 'rails', '3.0.0'
+
+gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'
+gem 'devise'
+gem 'nifty-generators'
+gem 'omniauth'
+gem 'mongrel', '1.2.0.pre2'
View
137 episode-236/todo/Gemfile.lock
@@ -0,0 +1,137 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ abstract (1.0.0)
+ actionmailer (3.0.0)
+ actionpack (= 3.0.0)
+ mail (~> 2.2.5)
+ actionpack (3.0.0)
+ activemodel (= 3.0.0)
+ activesupport (= 3.0.0)
+ builder (~> 2.1.2)
+ erubis (~> 2.6.6)
+ i18n (~> 0.4.1)
+ rack (~> 1.2.1)
+ rack-mount (~> 0.6.12)
+ rack-test (~> 0.5.4)
+ tzinfo (~> 0.3.23)
+ activemodel (3.0.0)
+ activesupport (= 3.0.0)
+ builder (~> 2.1.2)
+ i18n (~> 0.4.1)
+ activerecord (3.0.0)
+ activemodel (= 3.0.0)
+ activesupport (= 3.0.0)
+ arel (~> 1.0.0)
+ tzinfo (~> 0.3.23)
+ activeresource (3.0.0)
+ activemodel (= 3.0.0)
+ activesupport (= 3.0.0)
+ activesupport (3.0.0)
+ addressable (2.2.2)
+ arel (1.0.1)
+ activesupport (~> 3.0.0)
+ bcrypt-ruby (2.1.2)
+ builder (2.1.2)
+ daemons (1.0.10)
+ devise (1.1.3)
+ bcrypt-ruby (~> 2.1.2)
+ warden (~> 0.10.7)
+ erubis (2.6.6)
+ abstract (>= 1.0.0)
+ faraday (0.4.6)
+ addressable (>= 2.1.1)
+ rack (>= 1.0.1)
+ gem_plugin (0.2.3)
+ i18n (0.4.1)
+ mail (2.2.7)
+ activesupport (>= 2.3.6)
+ mime-types
+ treetop (>= 1.4.5)
+ mime-types (1.16)
+ mongrel (1.2.0.pre2)
+ daemons (~> 1.0.10)
+ gem_plugin (~> 0.2.3)
+ multi_json (0.0.4)
+ net-ldap (0.1.1)
+ nifty-generators (0.4.1)
+ nokogiri (1.4.3.1)
+ oa-basic (0.1.4)
+ multi_json (~> 0.0.2)
+ nokogiri (~> 1.4.2)
+ oa-core (= 0.1.4)
+ rest-client (~> 1.6.0)
+ oa-core (0.1.4)
+ rack (~> 1.1)
+ oa-enterprise (0.1.4)
+ net-ldap (~> 0.1.1)
+ nokogiri (~> 1.4.2)
+ oa-core (= 0.1.4)
+ rubyntlm (~> 0.1.1)
+ oa-oauth (0.1.4)
+ multi_json (~> 0.0.2)
+ nokogiri (~> 1.4.2)
+ oa-core (= 0.1.4)
+ oauth (~> 0.4.0)
+ oauth2 (~> 0.0.10)
+ oa-openid (0.1.4)
+ oa-core (= 0.1.4)
+ rack-openid (~> 1.1.1)
+ ruby-openid-apps-discovery
+ oauth (0.4.3)
+ oauth2 (0.0.13)
+ faraday (~> 0.4.1)
+ multi_json (>= 0.0.4)
+ omniauth (0.1.4)
+ oa-basic (= 0.1.4)
+ oa-core (= 0.1.4)
+ oa-enterprise (= 0.1.4)
+ oa-oauth (= 0.1.4)
+ oa-openid (= 0.1.4)
+ polyglot (0.3.1)
+ rack (1.2.1)
+ rack-mount (0.6.13)
+ rack (>= 1.0.0)
+ rack-openid (1.1.2)
+ rack (>= 0.4)
+ ruby-openid (>= 2.0.3)
+ rack-test (0.5.6)
+ rack (>= 1.0)
+ rails (3.0.0)
+ actionmailer (= 3.0.0)
+ actionpack (= 3.0.0)
+ activerecord (= 3.0.0)
+ activeresource (= 3.0.0)
+ activesupport (= 3.0.0)
+ bundler (~> 1.0.0)
+ railties (= 3.0.0)
+ railties (3.0.0)
+ actionpack (= 3.0.0)
+ activesupport (= 3.0.0)
+ rake (>= 0.8.4)
+ thor (~> 0.14.0)
+ rake (0.8.7)
+ rest-client (1.6.1)
+ mime-types (>= 1.16)
+ ruby-openid (2.1.8)
+ ruby-openid-apps-discovery (1.2.0)
+ ruby-openid (>= 2.1.7)
+ rubyntlm (0.1.1)
+ sqlite3-ruby (1.2.5)
+ thor (0.14.3)
+ treetop (1.4.8)
+ polyglot (>= 0.3.1)
+ tzinfo (0.3.23)
+ warden (0.10.7)
+ rack (>= 1.0.0)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ devise
+ mongrel (= 1.2.0.pre2)
+ nifty-generators
+ omniauth
+ rails (= 3.0.0)
+ sqlite3-ruby (= 1.2.5)
View
256 episode-236/todo/README
@@ -0,0 +1,256 @@
+== Welcome to Rails
+
+Rails is a web-application framework that includes everything needed to create
+database-backed web applications according to the Model-View-Control pattern.
+
+This pattern splits the view (also called the presentation) into "dumb"
+templates that are primarily responsible for inserting pre-built data in between
+HTML tags. The model contains the "smart" domain objects (such as Account,
+Product, Person, Post) that holds all the business logic and knows how to
+persist themselves to a database. The controller handles the incoming requests
+(such as Save New Account, Update Product, Show Post) by manipulating the model
+and directing data to the view.
+
+In Rails, the model is handled by what's called an object-relational mapping
+layer entitled Active Record. This layer allows you to present the data from
+database rows as objects and embellish these data objects with business logic
+methods. You can read more about Active Record in
+link:files/vendor/rails/activerecord/README.html.
+
+The controller and view are handled by the Action Pack, which handles both
+layers by its two parts: Action View and Action Controller. These two layers
+are bundled in a single package due to their heavy interdependence. This is
+unlike the relationship between the Active Record and Action Pack that is much
+more separate. Each of these packages can be used independently outside of
+Rails. You can read more about Action Pack in
+link:files/vendor/rails/actionpack/README.html.
+
+
+== Getting Started
+
+1. At the command prompt, create a new Rails application:
+ <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
+
+2. Change directory to <tt>myapp</tt> and start the web server:
+ <tt>cd myapp; rails server</tt> (run with --help for options)
+
+3. Go to http://localhost:3000/ and you'll see:
+ "Welcome aboard: You're riding Ruby on Rails!"
+
+4. Follow the guidelines to start developing your application. You can find
+the following resources handy:
+
+* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
+* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
+
+
+== Debugging Rails
+
+Sometimes your application goes wrong. Fortunately there are a lot of tools that
+will help you debug it and get it back on the rails.
+
+First area to check is the application log files. Have "tail -f" commands
+running on the server.log and development.log. Rails will automatically display
+debugging and runtime information to these files. Debugging info will also be
+shown in the browser on requests from 127.0.0.1.
+
+You can also log your own messages directly into the log file from your code
+using the Ruby logger class from inside your controllers. Example:
+
+ class WeblogController < ActionController::Base
+ def destroy
+ @weblog = Weblog.find(params[:id])
+ @weblog.destroy
+ logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
+ end
+ end
+
+The result will be a message in your log file along the lines of:
+
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
+
+More information on how to use the logger is at http://www.ruby-doc.org/core/
+
+Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
+several books available online as well:
+
+* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
+* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
+
+These two books will bring you up to speed on the Ruby language and also on
+programming in general.
+
+
+== Debugger
+
+Debugger support is available through the debugger command when you start your
+Mongrel or WEBrick server with --debugger. This means that you can break out of
+execution at any point in the code, investigate and change the model, and then,
+resume execution! You need to install ruby-debug to run the server in debugging
+mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find(:all)
+ debugger
+ end
+ end
+
+So the controller will accept the action, run the first line, then present you
+with a IRB prompt in the server window. Here you can do things like:
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8
+ @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
+ #<Post:0x14a6620
+ @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
+ >> @posts.first.title = "hello from a debugger"
+ => "hello from a debugger"
+
+...and even better, you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+Finally, when you're ready to resume execution, you can enter "cont".
+
+
+== Console
+
+The console is a Ruby shell, which allows you to interact with your
+application's domain model. Here you'll have all parts of the application
+configured, just like it is when the application is running. You can inspect
+domain models, change values, and save to the database. Starting the script
+without arguments will launch it in the development environment.
+
+To start the console, run <tt>rails console</tt> from the application
+directory.
+
+Options:
+
+* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
+ made to the database.
+* Passing an environment name as an argument will load the corresponding
+ environment. Example: <tt>rails console production</tt>.
+
+To reload your controllers and models after launching the console run
+<tt>reload!</tt>
+
+More information about irb can be found at:
+link:http://www.rubycentral.com/pickaxe/irb.html
+
+
+== dbconsole
+
+You can go to the command line of your database directly through <tt>rails
+dbconsole</tt>. You would be connected to the database with the credentials
+defined in database.yml. Starting the script without arguments will connect you
+to the development database. Passing an argument will connect you to a different
+database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
+PostgreSQL and SQLite 3.
+
+== Description of Contents
+
+The default directory structure of a generated Ruby on Rails application:
+
+ |-- app
+ | |-- controllers
+ | |-- helpers
+ | |-- models
+ | `-- views
+ | `-- layouts
+ |-- config
+ | |-- environments
+ | |-- initializers
+ | `-- locales
+ |-- db
+ |-- doc
+ |-- lib
+ | `-- tasks
+ |-- log
+ |-- public
+ | |-- images
+ | |-- javascripts
+ | `-- stylesheets
+ |-- script
+ | `-- performance
+ |-- test
+ | |-- fixtures
+ | |-- functional
+ | |-- integration
+ | |-- performance
+ | `-- unit
+ |-- tmp
+ | |-- cache
+ | |-- pids
+ | |-- sessions
+ | `-- sockets
+ `-- vendor
+ `-- plugins
+
+app
+ Holds all the code that's specific to this particular application.
+
+app/controllers
+ Holds controllers that should be named like weblogs_controller.rb for
+ automated URL mapping. All controllers should descend from
+ ApplicationController which itself descends from ActionController::Base.
+
+app/models
+ Holds models that should be named like post.rb. Models descend from
+ ActiveRecord::Base by default.
+
+app/views
+ Holds the template files for the view that should be named like
+ weblogs/index.html.erb for the WeblogsController#index action. All views use
+ eRuby syntax by default.
+
+app/views/layouts
+ Holds the template files for layouts to be used with views. This models the
+ common header/footer method of wrapping views. In your views, define a layout
+ using the <tt>layout :default</tt> and create a file named default.html.erb.
+ Inside default.html.erb, call <% yield %> to render the view using this
+ layout.
+
+app/helpers
+ Holds view helpers that should be named like weblogs_helper.rb. These are
+ generated for you automatically when using generators for controllers.
+ Helpers can be used to wrap functionality for your views into methods.
+
+config
+ Configuration files for the Rails environment, the routing map, the database,
+ and other dependencies.
+
+db
+ Contains the database schema in schema.rb. db/migrate contains all the
+ sequence of Migrations for your schema.
+
+doc
+ This directory is where your application documentation will be stored when
+ generated using <tt>rake doc:app</tt>
+
+lib
+ Application specific libraries. Basically, any kind of custom code that
+ doesn't belong under controllers, models, or helpers. This directory is in
+ the load path.
+
+public
+ The directory available for the web server. Contains subdirectories for
+ images, stylesheets, and javascripts. Also contains the dispatchers and the
+ default HTML files. This should be set as the DOCUMENT_ROOT of your web
+ server.
+
+script
+ Helper scripts for automation and generation.
+
+test
+ Unit and functional tests along with fixtures. When using the rails generate
+ command, template test files will be generated for you and placed in this
+ directory.
+
+vendor
+ External libraries that the application depends on. Also includes the plugins
+ subdirectory. If the app has frozen rails, those gems also go here, under
+ vendor/rails/. This directory is in the load path.
View
7 episode-236/todo/Rakefile
@@ -0,0 +1,7 @@
+# Add your own tasks in files placed in lib/tasks ending in .rake,
+# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
+
+require File.expand_path('../config/application', __FILE__)
+require 'rake'
+
+Todo::Application.load_tasks
View
3  episode-236/todo/app/controllers/application_controller.rb
@@ -0,0 +1,3 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+end
View
35 episode-236/todo/app/controllers/authentications_controller.rb
@@ -0,0 +1,35 @@
+class AuthenticationsController < ApplicationController
+ def index
+ @authentications = current_user.authentications if current_user
+ end
+
+ def create
+ omniauth = request.env["omniauth.auth"]
+ authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
+ if authentication
+ flash[:notice] = "Signed in successfully."
+ sign_in_and_redirect(:user, authentication.user)
+ elsif current_user
+ current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
+ flash[:notice] = "Authentication successful."
+ redirect_to authentications_url
+ else
+ user = User.new
+ user.apply_omniauth(omniauth)
+ if user.save
+ flash[:notice] = "Signed in successfully."
+ sign_in_and_redirect(:user, user)
+ else
+ session[:omniauth] = omniauth.except('extra')
+ redirect_to new_user_registration_url
+ end
+ end
+ end
+
+ def destroy
+ @authentication = current_user.authentications.find(params[:id])
+ @authentication.destroy
+ flash[:notice] = "Successfully destroyed authentication."
+ redirect_to authentications_url
+ end
+end
View
44 episode-236/todo/app/controllers/projects_controller.rb
@@ -0,0 +1,44 @@
+class ProjectsController < ApplicationController
+ def index
+ @projects = Project.all
+ end
+
+ def show
+ @project = Project.find(params[:id])
+ end
+
+ def new
+ @project = Project.new
+ end
+
+ def create
+ @project = Project.new(params[:project])
+ if @project.save
+ flash[:notice] = "Successfully created project."
+ redirect_to @project
+ else
+ render :action => 'new'
+ end
+ end
+
+ def edit
+ @project = Project.find(params[:id])
+ end
+
+ def update
+ @project = Project.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 = Project.find(params[:id])
+ @project.destroy
+ flash[:notice] = "Successfully destroyed project."
+ redirect_to projects_url
+ end
+end
View
16 episode-236/todo/app/controllers/registrations_controller.rb
@@ -0,0 +1,16 @@
+class RegistrationsController < Devise::RegistrationsController
+ def create
+ super
+ session[:omniauth] = nil unless @user.new_record?
+ end
+
+ private
+
+ def build_resource(*args)
+ super
+ if session[:omniauth]
+ @user.apply_omniauth(session[:omniauth])
+ @user.valid?
+ end
+ end
+end
View
36 episode-236/todo/app/controllers/tasks_controller.rb
@@ -0,0 +1,36 @@
+class TasksController < ApplicationController
+ def new
+ @task = Task.new(:project_id => params[:project_id])
+ end
+
+ def create
+ @task = Task.new(params[:task])
+ if @task.save
+ flash[:notice] = "Successfully created task."
+ redirect_to @task.project
+ else
+ render :action => 'new'
+ end
+ end
+
+ def edit
+ @task = Task.find(params[:id])
+ end
+
+ def update
+ @task = Task.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
+ @task = Task.find(params[:id])
+ @task.destroy
+ flash[:notice] = "Successfully destroyed task."
+ redirect_to @task.project
+ end
+end
View
2  episode-236/todo/app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
View
2  episode-236/todo/app/helpers/authentications_helper.rb
@@ -0,0 +1,2 @@
+module AuthenticationsHelper
+end
View
23 episode-236/todo/app/helpers/error_messages_helper.rb
@@ -0,0 +1,23 @@
+module ErrorMessagesHelper
+ # Render error messages for the given objects. The :message and :header_message options are allowed.
+ def error_messages_for(*objects)
+ options = objects.extract_options!
+ options[:header_message] ||= "Invalid Fields"
+ options[:message] ||= "Correct the following errors and try again."
+ messages = objects.compact.map { |o| o.errors.full_messages }.flatten
+ unless messages.empty?
+ content_tag(:div, :class => "error_messages") do
+ list_items = messages.map { |msg| content_tag(:li, msg) }
+ content_tag(:h2, options[:header_message]) + content_tag(:p, options[:message]) + content_tag(:ul, list_items.join.html_safe)
+ end
+ end
+ end
+
+ module FormBuilderAdditions
+ def error_messages(options = {})
+ @template.error_messages_for(@object, options)
+ end
+ end
+end
+
+ActionView::Helpers::FormBuilder.send(:include, ErrorMessagesHelper::FormBuilderAdditions)
View
22 episode-236/todo/app/helpers/layout_helper.rb
@@ -0,0 +1,22 @@
+# These helper methods can be called in your template to set variables to be used in the layout
+# This module should be included in all views globally,
+# to do so you may need to add this line to your ApplicationController
+# helper :layout
+module LayoutHelper
+ def title(page_title, show_title = true)
+ content_for(:title) { page_title.to_s }
+ @show_title = show_title
+ end
+
+ def show_title?
+ @show_title
+ end
+
+ def stylesheet(*args)
+ content_for(:head) { stylesheet_link_tag(*args) }
+ end
+
+ def javascript(*args)
+ content_for(:head) { javascript_include_tag(*args) }
+ end
+end
View
2  episode-236/todo/app/helpers/projects_helper.rb
@@ -0,0 +1,2 @@
+module ProjectsHelper
+end
View
2  episode-236/todo/app/helpers/registrations_helper.rb
@@ -0,0 +1,2 @@
+module RegistrationsHelper
+end
View
2  episode-236/todo/app/helpers/tasks_helper.rb
@@ -0,0 +1,2 @@
+module TasksHelper
+end
View
11 episode-236/todo/app/models/authentication.rb
@@ -0,0 +1,11 @@
+class Authentication < ActiveRecord::Base
+ belongs_to :user
+
+ def provider_name
+ if provider == 'open_id'
+ "OpenID"
+ else
+ provider.titleize
+ end
+ end
+end
View
4 episode-236/todo/app/models/project.rb
@@ -0,0 +1,4 @@
+class Project < ActiveRecord::Base
+ attr_accessible :name
+ has_many :tasks
+end
View
4 episode-236/todo/app/models/task.rb
@@ -0,0 +1,4 @@
+class Task < ActiveRecord::Base
+ attr_accessible :project_id, :name, :completed_at
+ belongs_to :project
+end
View
20 episode-236/todo/app/models/user.rb
@@ -0,0 +1,20 @@
+class User < ActiveRecord::Base
+ has_many :authentications
+
+ # Include default devise modules. Others available are:
+ # :token_authenticatable, :confirmable, :lockable and :timeoutable
+ devise :database_authenticatable, :registerable,
+ :recoverable, :rememberable, :trackable, :validatable
+
+ # Setup accessible (or protected) attributes for your model
+ attr_accessible :email, :password, :password_confirmation, :remember_me
+
+ def apply_omniauth(omniauth)
+ self.email = omniauth['user_info']['email'] if email.blank?
+ authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
+ end
+
+ def password_required?
+ (authentications.empty? || !password.blank?) && super
+ end
+end
View
47 episode-236/todo/app/views/authentications/index.html.erb
@@ -0,0 +1,47 @@
+<% title "Sign In Options" %>
+
+<% if @authentications %>
+ <% unless @authentications.empty? %>
+ <p><strong>You have signed in with these services:</strong></p>
+ <div class="authentications">
+ <% for authentication in @authentications %>
+ <div class="authentication">
+ <%= image_tag "#{authentication.provider}_32.png", :size => "32x32" %>
+ <div class="provider"><%= authentication.provider_name %></div>
+ <div class="uid"><%= authentication.uid %></div>
+ <%= link_to "X", authentication, :confirm => 'Are you sure you want to remove this authentication option?', :method => :delete, :class => "remove" %>
+ </div>
+ <% end %>
+ <div class="clear"></div>
+ </div>
+ <% end %>
+ <p><strong>Add another service to sign in with:</strong></p>
+<% else %>
+ <p><strong>Sign in through one of these services:</strong></p>
+<% end %>
+
+<a href="/auth/twitter" class="auth_provider">
+ <%= image_tag "twitter_64.png", :size => "64x64", :alt => "Twitter" %>
+ Twitter
+</a>
+<a href="/auth/facebook" class="auth_provider">
+ <%= image_tag "facebook_64.png", :size => "64x64", :alt => "Facebook" %>
+ Facebook
+</a>
+<a href="/auth/google_apps" class="auth_provider">
+ <%= image_tag "google_apps_64.png", :size => "64x64", :alt => "Google" %>
+ Google
+</a>
+<a href="/auth/open_id" class="auth_provider">
+ <%= image_tag "open_id_64.png", :size => "64x64", :alt => "OpenID" %>
+ OpenID
+</a>
+<div class="clear"></div>
+
+<% unless user_signed_in? %>
+ <p>
+ <strong>Don't use these services?</strong>
+ <%= link_to "Sign up", new_user_registration_path %> or
+ <%= link_to "sign in", new_user_session_path %> with a password.
+ </p>
+<% end %>
View
12 episode-236/todo/app/views/devise/confirmations/new.html.erb
@@ -0,0 +1,12 @@
+<h2>Resend confirmation instructions</h2>
+
+<%= form_for(resource, :as => resource_name, :url => confirmation_path(resource_name), :html => { :method => :post }) do |f| %>
+ <%= devise_error_messages! %>
+
+ <p><%= f.label :email %><br />
+ <%= f.text_field :email %></p>
+
+ <p><%= f.submit "Resend confirmation instructions" %></p>
+<% end %>
+
+<%= render :partial => "devise/shared/links" %>
View
5 episode-236/todo/app/views/devise/mailer/confirmation_instructions.html.erb
@@ -0,0 +1,5 @@
+<p>Welcome <%= @resource.email %>!</p>
+
+<p>You can confirm your account through the link below:</p>
+
+<p><%= link_to 'Confirm my account', confirmation_url(@resource, :confirmation_token => @resource.confirmation_token) %></p>
View
8 episode-236/todo/app/views/devise/mailer/reset_password_instructions.html.erb
@@ -0,0 +1,8 @@
+<p>Hello <%= @resource.email %>!</p>
+
+<p>Someone has requested a link to change your password, and you can do this through the link below.</p>
+
+<p><%= link_to 'Change my password', edit_password_url(@resource, :reset_password_token => @resource.reset_password_token) %></p>
+
+<p>If you didn't request this, please ignore this email.</p>
+<p>Your password won't change until you access the link above and create a new one.</p>
View
7 episode-236/todo/app/views/devise/mailer/unlock_instructions.html.erb
@@ -0,0 +1,7 @@
+<p>Hello <%= @resource.email %>!</p>
+
+<p>Your account has been locked due to an excessive amount of unsuccessful sign in attempts.</p>
+
+<p>Click the link below to unlock your account:</p>
+
+<p><%= link_to 'Unlock my account', unlock_url(@resource, :unlock_token => @resource.unlock_token) %></p>
View
16 episode-236/todo/app/views/devise/passwords/edit.html.erb
@@ -0,0 +1,16 @@
+<h2>Change your password</h2>
+
+<%= form_for(resource, :as => resource_name, :url => password_path(resource_name), :html => { :method => :put }) do |f| %>
+ <%= devise_error_messages! %>
+ <%= f.hidden_field :reset_password_token %>
+
+ <p><%= f.label :password %><br />
+ <%= f.password_field :password %></p>
+
+ <p><%= f.label :password_confirmation %><br />
+ <%= f.password_field :password_confirmation %></p>
+
+ <p><%= f.submit "Change my password" %></p>
+<% end %>
+
+<%= render :partial => "devise/shared/links" %>
View
12 episode-236/todo/app/views/devise/passwords/new.html.erb
@@ -0,0 +1,12 @@
+<h2>Forgot your password?</h2>
+
+<%= form_for(resource, :as => resource_name, :url => password_path(resource_name), :html => { :method => :post }) do |f| %>
+ <%= devise_error_messages! %>
+
+ <p><%= f.label :email %><br />
+ <%= f.text_field :email %></p>
+
+ <p><%= f.submit "Send me reset password instructions" %></p>
+<% end %>
+
+<%= render :partial => "devise/shared/links" %>
View
17 episode-236/todo/app/views/devise/sessions/new.html.erb
@@ -0,0 +1,17 @@
+<h2>Sign in</h2>
+
+<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
+ <p><%= f.label :email %><br />
+ <%= f.text_field :email %></p>
+
+ <p><%= f.label :password %><br />
+ <%= f.password_field :password %></p>
+
+ <% if devise_mapping.rememberable? -%>
+ <p><%= f.check_box :remember_me %> <%= f.label :remember_me %></p>
+ <% end -%>
+
+ <p><%= f.submit "Sign in" %></p>
+<% end %>
+
+<%= render :partial => "devise/shared/links" %>
View
19 episode-236/todo/app/views/devise/shared/_links.erb
@@ -0,0 +1,19 @@
+<%- if controller_name != 'sessions' %>
+ <%= link_to "Sign in", new_session_path(resource_name) %><br />
+<% end -%>
+
+<%- if devise_mapping.registerable? && controller_name != 'registrations' %>
+ <%= link_to "Sign up", new_registration_path(resource_name) %><br />
+<% end -%>
+
+<%- if devise_mapping.recoverable? && controller_name != 'passwords' %>
+ <%= link_to "Forgot your password?", new_password_path(resource_name) %><br />
+<% end -%>
+
+<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %>
+ <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %><br />
+<% end -%>
+
+<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %>
+ <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %><br />
+<% end -%>
View
12 episode-236/todo/app/views/devise/unlocks/new.html.erb
@@ -0,0 +1,12 @@
+<h2>Resend unlock instructions</h2>
+
+<%= form_for(resource, :as => resource_name, :url => unlock_path(resource_name), :html => { :method => :post }) do |f| %>
+ <%= devise_error_messages! %>
+
+ <p><%= f.label :email %><br />
+ <%= f.text_field :email %></p>
+
+ <p><%= f.submit "Resend unlock instructions" %></p>
+<% end %>
+
+<%= render :partial => "devise/shared/links" %>
View
27 episode-236/todo/app/views/layouts/application.html.erb
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
+ <%= stylesheet_link_tag "application" %>
+ <%= javascript_include_tag :defaults %>
+ <%= csrf_meta_tag %>
+ <%= yield(:head) %>
+ </head>
+ <body>
+ <div id="container">
+ <div id="user_nav">
+ <% if user_signed_in? %>
+ Signed in as <%= current_user.email %>.<br />
+ Not you? <%= link_to "Sign out", destroy_user_session_path %>
+ <% else %>
+ <%= link_to "Sign In", authentications_path %>
+ <% end %>
+ </div>
+ <% flash.each do |name, msg| %>
+ <%= content_tag :div, msg, :id => "flash_#{name}" %>
+ <% end %>
+ <%= content_tag :h1, yield(:title) if show_title? %>
+ <%= yield %>
+ </div>
+ </body>
+</html>
View
8 episode-236/todo/app/views/projects/_form.html.erb
@@ -0,0 +1,8 @@
+<%= form_for @project do |f| %>
+ <%= f.error_messages %>
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p><%= f.submit %></p>
+<% end %>
View
8 episode-236/todo/app/views/projects/edit.html.erb
@@ -0,0 +1,8 @@
+<% title "Edit Project" %>
+
+<%= render 'form' %>
+
+<p>
+ <%= link_to "Show", @project %> |
+ <%= link_to "View All", projects_path %>
+</p>
View
16 episode-236/todo/app/views/projects/index.html.erb
@@ -0,0 +1,16 @@
+<% title "Projects" %>
+
+<table>
+ <tr>
+ <th>Name</th>
+ </tr>
+ <% for project in @projects %>
+ <tr>
+ <td><%= link_to project.name, project %></td>
+ <td><%= link_to "Edit", edit_project_path(project) %></td>
+ <td><%= link_to "Destroy", project, :confirm => 'Are you sure?', :method => :delete %></td>
+ </tr>
+ <% end %>
+</table>
+
+<p><%= link_to "New Project", new_project_path %></p>
View
5 episode-236/todo/app/views/projects/new.html.erb
@@ -0,0 +1,5 @@
+<% title "New Project" %>
+
+<%= render 'form' %>
+
+<p><%= link_to "Back to List", projects_path %></p>
View
17 episode-236/todo/app/views/projects/show.html.erb
@@ -0,0 +1,17 @@
+<% title @project.name %>
+
+<h2>Tasks</h2>
+<ul>
+ <% for task in @project.tasks %>
+ <li>
+ <%= task.name %>
+ (<%= link_to "Edit", edit_task_path(task) %> |
+ <%= link_to "Destroy", task, :confirm => "Are you sure?", :method => :delete %>)
+ </li>
+ <% end %>
+</ul>
+
+<p>
+ <%= link_to "New Task", new_task_path(:project_id => @project) %> |
+ <%= link_to "View All Projects", projects_path %>
+</p>
View
25 episode-236/todo/app/views/registrations/edit.html.erb
@@ -0,0 +1,25 @@
+<h2>Edit <%= resource_name.to_s.humanize %></h2>
+
+<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>
+ <%= devise_error_messages! %>
+
+ <p><%= f.label :email %><br />
+ <%= f.text_field :email %></p>
+
+ <p><%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
+ <%= f.password_field :password %></p>
+
+ <p><%= f.label :password_confirmation %><br />
+ <%= f.password_field :password_confirmation %></p>
+
+ <p><%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
+ <%= f.password_field :current_password %></p>
+
+ <p><%= f.submit "Update" %></p>
+<% end %>
+
+<h3>Cancel my account</h3>
+
+<p>Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), :confirm => "Are you sure?", :method => :delete %>.</p>
+
+<%= link_to "Back", :back %>
View
20 episode-236/todo/app/views/registrations/new.html.erb
@@ -0,0 +1,20 @@
+<h2>Sign up</h2>
+
+<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
+ <%= devise_error_messages! %>
+
+ <p><%= f.label :email %><br />
+ <%= f.text_field :email %></p>
+
+<% if @user.password_required? %>
+ <p><%= f.label :password %><br />
+ <%= f.password_field :password %></p>
+
+ <p><%= f.label :password_confirmation %><br />
+ <%= f.password_field :password_confirmation %></p>
+<% end %>
+
+ <p><%= f.submit "Sign up" %></p>
+<% end %>
+
+<%= render :partial => "devise/shared/links" %>
View
13 episode-236/todo/app/views/tasks/_form.html.erb
@@ -0,0 +1,13 @@
+<%= form_for @task do |f| %>
+ <%= f.hidden_field :project_id %>
+ <%= f.error_messages %>
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.label :completed_at %><br />
+ <%= f.date_select :completed_at %>
+ </p>
+ <p><%= f.submit %></p>
+<% end %>
View
4 episode-236/todo/app/views/tasks/edit.html.erb
@@ -0,0 +1,4 @@
+<% title "Edit Task" %>
+
+<%= render 'form' %>
+
View
4 episode-236/todo/app/views/tasks/new.html.erb
@@ -0,0 +1,4 @@
+<% title "New Task" %>
+
+<%= render 'form' %>
+
View
4 episode-236/todo/config.ru
@@ -0,0 +1,4 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+run Todo::Application
View
42 episode-236/todo/config/application.rb
@@ -0,0 +1,42 @@
+require File.expand_path('../boot', __FILE__)
+
+require 'rails/all'
+
+# If you have a Gemfile, require the gems listed there, including any gems
+# you've limited to :test, :development, or :production.
+Bundler.require(:default, Rails.env) if defined?(Bundler)
+
+module Todo
+ class Application < Rails::Application
+ # Settings in config/environments/* take precedence over those specified here.
+ # Application configuration should go into files in config/initializers
+ # -- all .rb files in that directory are automatically loaded.
+
+ # Custom directories with classes and modules you want to be autoloadable.
+ # config.autoload_paths += %W(#{config.root}/extras)
+
+ # Only load the plugins named here, in the order given (default is alphabetical).
+ # :all can be used as a placeholder for all plugins not explicitly named.
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
+
+ # Activate observers that should always be running.
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
+
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
+ # config.time_zone = 'Central Time (US & Canada)'
+
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
+ # config.i18n.default_locale = :de
+
+ # JavaScript files you want as :defaults (application.js is always included).
+ # config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
+
+ # Configure the default encoding used in templates for Ruby 1.9.
+ config.encoding = "utf-8"
+
+ # Configure sensitive parameters which will be filtered from the log file.
+ config.filter_parameters += [:password]
+ end
+end
View
13 episode-236/todo/config/boot.rb
@@ -0,0 +1,13 @@
+require 'rubygems'
+
+# Set up gems listed in the Gemfile.
+gemfile = File.expand_path('../../Gemfile', __FILE__)
+begin
+ ENV['BUNDLE_GEMFILE'] = gemfile
+ require 'bundler'
+ Bundler.setup
+rescue Bundler::GemNotFound => e
+ STDERR.puts e.message
+ STDERR.puts "Try running `bundle install`."
+ exit!
+end if File.exist?(gemfile)
View
22 episode-236/todo/config/database.yml
@@ -0,0 +1,22 @@
+# SQLite version 3.x
+# gem install sqlite3-ruby (not necessary on OS X Leopard)
+development:
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
+ timeout: 5000
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: sqlite3
+ database: db/test.sqlite3
+ pool: 5
+ timeout: 5000
+
+production:
+ adapter: sqlite3
+ database: db/production.sqlite3
+ pool: 5
+ timeout: 5000
View
5 episode-236/todo/config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application
+Todo::Application.initialize!
View
27 episode-236/todo/config/environments/development.rb
@@ -0,0 +1,27 @@
+Todo::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # In the development environment your application's code is reloaded on
+ # every request. This slows down response time but is perfect for development
+ # since you don't have to restart the webserver when you make code changes.
+ config.cache_classes = false
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_view.debug_rjs = true
+ config.action_controller.perform_caching = false
+
+ # Don't care if the mailer can't send
+ config.action_mailer.raise_delivery_errors = false
+
+ # Print deprecation notices to the Rails logger
+ config.active_support.deprecation = :log
+
+ # Only use best-standards-support built into browsers
+ config.action_dispatch.best_standards_support = :builtin
+
+ config.action_mailer.default_url_options = { :host => 'localhost:3000' }
+end
View
49 episode-236/todo/config/environments/production.rb
@@ -0,0 +1,49 @@
+Todo::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # The production environment is meant for finished, "live" apps.
+ # Code is not reloaded between requests
+ config.cache_classes = true
+
+ # Full error reports are disabled and caching is turned on
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # Specifies the header that your server uses for sending files
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
+
+ # For nginx:
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
+
+ # If you have no front-end server that supports something like X-Sendfile,
+ # just comment this out and Rails will serve the files
+
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
+
+ # Use a different logger for distributed setups
+ # config.logger = SyslogLogger.new
+
+ # Use a different cache store in production
+ # config.cache_store = :mem_cache_store
+
+ # Disable Rails's static asset server
+ # In production, Apache or nginx will already do this
+ config.serve_static_assets = false
+
+ # Enable serving of images, stylesheets, and javascripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Disable delivery errors, bad email addresses will be ignored
+ # config.action_mailer.raise_delivery_errors = false
+
+ # Enable threaded mode
+ # config.threadsafe!
+
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
+ # the I18n.default_locale when a translation can not be found)
+ config.i18n.fallbacks = true
+
+ # Send deprecation notices to registered listeners
+ config.active_support.deprecation = :notify
+end
View
35 episode-236/todo/config/environments/test.rb
@@ -0,0 +1,35 @@
+Todo::Application.configure do
+ # Settings specified here will take precedence over those in config/environment.rb
+
+ # The test environment is used exclusively to run your application's
+ # test suite. You never need to work with it otherwise. Remember that
+ # your test database is "scratch space" for the test suite and is wiped
+ # and recreated between test runs. Don't rely on the data there!
+ config.cache_classes = true
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_controller.perform_caching = false
+
+ # Raise exceptions instead of rendering exception templates
+ config.action_dispatch.show_exceptions = false
+
+ # Disable request forgery protection in test environment
+ config.action_controller.allow_forgery_protection = false
+
+ # Tell Action Mailer not to deliver emails to the real world.
+ # The :test delivery method accumulates sent emails in the
+ # ActionMailer::Base.deliveries array.
+ config.action_mailer.delivery_method = :test
+
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ # config.active_record.schema_format = :sql
+
+ # Print deprecation notices to the stderr
+ config.active_support.deprecation = :stderr
+end
View
7 episode-236/todo/config/initializers/backtrace_silencers.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
+# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
+
+# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
+# Rails.backtrace_cleaner.remove_silencers!
View
142 episode-236/todo/config/initializers/devise.rb
@@ -0,0 +1,142 @@
+# Use this hook to configure devise mailer, warden hooks and so forth. The first
+# four configuration values can also be set straight in your models.
+Devise.setup do |config|
+ # ==> Mailer Configuration
+ # Configure the e-mail address which will be shown in DeviseMailer.
+ config.mailer_sender = "please-change-me@config-initializers-devise.com"
+
+ # Configure the class responsible to send e-mails.
+ # config.mailer = "Devise::Mailer"
+
+ # ==> ORM configuration
+ # Load and configure the ORM. Supports :active_record (default) and
+ # :mongoid (bson_ext recommended) by default. Other ORMs may be
+ # available as additional gems.
+ require 'devise/orm/active_record'
+
+ # ==> Configuration for any authentication mechanism
+ # Configure which keys are used when authenticating an user. By default is
+ # just :email. You can configure it to use [:username, :subdomain], so for
+ # authenticating an user, both parameters are required. Remember that those
+ # parameters are used only when authenticating and not when retrieving from
+ # session. If you need permissions, you should implement that in a before filter.
+ # config.authentication_keys = [ :email ]
+
+ # Tell if authentication through request.params is enabled. True by default.
+ # config.params_authenticatable = true
+
+ # Tell if authentication through HTTP Basic Auth is enabled. True by default.
+ # config.http_authenticatable = true
+
+ # Set this to true to use Basic Auth for AJAX requests. True by default.
+ # config.http_authenticatable_on_xhr = true
+
+ # The realm used in Http Basic Authentication
+ # config.http_authentication_realm = "Application"
+
+ # ==> Configuration for :database_authenticatable
+ # For bcrypt, this is the cost for hashing the password and defaults to 10. If
+ # using other encryptors, it sets how many times you want the password re-encrypted.
+ config.stretches = 10
+
+ # Define which will be the encryption algorithm. Devise also supports encryptors
+ # from others authentication tools as :clearance_sha1, :authlogic_sha512 (then
+ # you should set stretches above to 20 for default behavior) and :restful_authentication_sha1
+ # (then you should set stretches to 10, and copy REST_AUTH_SITE_KEY to pepper)
+ config.encryptor = :bcrypt
+
+ # Setup a pepper to generate the encrypted password.
+ config.pepper = "c0cccd076213dc4069806d76ae105d61acc7cb8274f4a382f02e283b6f65d053e3886f7015a4932685a1c08b0cdb3429978e2d35ffa34db5be905a2fd0617a2a"
+
+ # ==> Configuration for :confirmable
+ # The time you want to give your user to confirm his account. During this time
+ # he will be able to access your application without confirming. Default is nil.
+ # When confirm_within is zero, the user won't be able to sign in without confirming.
+ # You can use this to let your user access some features of your application
+ # without confirming the account, but blocking it after a certain period
+ # (ie 2 days).
+ # config.confirm_within = 2.days
+
+ # ==> Configuration for :rememberable
+ # The time the user will be remembered without asking for credentials again.
+ # config.remember_for = 2.weeks
+
+ # If true, a valid remember token can be re-used between multiple browsers.
+ # config.remember_across_browsers = true
+
+ # If true, extends the user's remember period when remembered via cookie.
+ # config.extend_remember_period = false
+
+ # ==> Configuration for :validatable
+ # Range for password length
+ # config.password_length = 6..20
+
+ # Regex to use to validate the email address
+ # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i
+
+ # ==> Configuration for :timeoutable
+ # The time you want to timeout the user session without activity. After this
+ # time the user will be asked for credentials again.
+ # config.timeout_in = 10.minutes
+
+ # ==> Configuration for :lockable
+ # Defines which strategy will be used to lock an account.
+ # :failed_attempts = Locks an account after a number of failed attempts to sign in.
+ # :none = No lock strategy. You should handle locking by yourself.
+ # config.lock_strategy = :failed_attempts
+
+ # Defines which strategy will be used to unlock an account.
+ # :email = Sends an unlock link to the user email
+ # :time = Re-enables login after a certain amount of time (see :unlock_in below)
+ # :both = Enables both strategies
+ # :none = No unlock strategy. You should handle unlocking by yourself.
+ # config.unlock_strategy = :both
+
+ # Number of authentication tries before locking an account if lock_strategy
+ # is failed attempts.
+ # config.maximum_attempts = 20
+
+ # Time interval to unlock the account if :time is enabled as unlock_strategy.
+ # config.unlock_in = 1.hour
+
+ # ==> Configuration for :token_authenticatable
+ # Defines name of the authentication token params key
+ # config.token_authentication_key = :auth_token
+
+ # ==> Scopes configuration
+ # Turn scoped views on. Before rendering "sessions/new", it will first check for
+ # "users/sessions/new". It's turned off by default because it's slower if you
+ # are using only default views.
+ # config.scoped_views = true
+
+ # Configure the default scope given to Warden. By default it's the first
+ # devise role declared in your routes.
+ # config.default_scope = :user
+
+ # Configure sign_out behavior.
+ # By default sign_out is scoped (i.e. /users/sign_out affects only :user scope).
+ # In case of sign_out_all_scopes set to true any logout action will sign out all active scopes.
+ # config.sign_out_all_scopes = false
+
+ # ==> Navigation configuration
+ # Lists the formats that should be treated as navigational. Formats like
+ # :html, should redirect to the sign in page when the user does not have
+ # access, but formats like :xml or :json, should return 401.
+ # If you have any extra navigational formats, like :iphone or :mobile, you
+ # should add them to the navigational formats lists. Default is [:html]
+ # config.navigational_formats = [:html, :iphone]
+
+ # ==> Warden configuration
+ # If you want to use other strategies, that are not (yet) supported by Devise,
+ # you can configure them inside the config.warden block. The example below
+ # allows you to setup OAuth, using http://github.com/roman/warden_oauth
+ #
+ # config.warden do |manager|
+ # manager.oauth(:twitter) do |twitter|
+ # twitter.consumer_secret = <YOUR CONSUMER SECRET>
+ # twitter.consumer_key = <YOUR CONSUMER KEY>
+ # twitter.options :site => 'http://twitter.com'
+ # end
+ # manager.default_strategies(:scope => :user).unshift :twitter_oauth
+ # end
+end
View
10 episode-236/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):
+# ActiveSupport::Inflector.inflections do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
View
5 episode-236/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
5 episode-236/todo/config/initializers/omniauth.rb
@@ -0,0 +1,5 @@
+require 'openid/store/filesystem'
+Rails.application.config.middleware.use OmniAuth::Builder do
+ provider :twitter, 'CONSUMER_KEY', 'CONSUMER_SECRET'
+ provider :open_id, OpenID::Store::Filesystem.new('/tmp')
+end
View
7 episode-236/todo/config/initializers/secret_token.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+Todo::Application.config.secret_token = '38bb547bb44bd1f26bb2a8a5125a51ee1e39676bcffbb000d7a4aa96a459b0c21ded17b16002e6a96a2b1ef30a79f8a2ae7c7832897db31bf1b02543d38396c1'
View
8 episode-236/todo/config/initializers/session_store.rb
@@ -0,0 +1,8 @@
+# Be sure to restart your server when you modify this file.
+
+Todo::Application.config.session_store :cookie_store, :key => '_todo_session'
+
+# Use the database for sessions instead of the cookie-based default,
+# which shouldn't be used to store highly confidential information
+# (create the session table with "rake db:sessions:create")
+# Todo::Application.config.session_store :active_record_store
View
39 episode-236/todo/config/locales/devise.en.yml
@@ -0,0 +1,39 @@
+en:
+ errors:
+ messages:
+ not_found: "not found"
+ already_confirmed: "was already confirmed"
+ not_locked: "was not locked"
+
+ devise:
+ failure:
+ unauthenticated: 'You need to sign in or sign up before continuing.'
+ unconfirmed: 'You have to confirm your account before continuing.'
+ locked: 'Your account is locked.'
+ invalid: 'Invalid email or password.'
+ invalid_token: 'Invalid authentication token.'
+ timeout: 'Your session expired, please sign in again to continue.'
+ inactive: 'Your account was not activated yet.'
+ sessions:
+ signed_in: 'Signed in successfully.'
+ signed_out: 'Signed out successfully.'
+ passwords:
+ send_instructions: 'You will receive an email with instructions about how to reset your password in a few minutes.'
+ updated: 'Your password was changed successfully. You are now signed in.'
+ confirmations:
+ send_instructions: 'You will receive an email with instructions about how to confirm your account in a few minutes.'
+ confirmed: 'Your account was successfully confirmed. You are now signed in.'
+ registrations:
+ signed_up: 'You have signed up successfully. If enabled, a confirmation was sent to your e-mail.'
+ updated: 'You updated your account successfully.'
+ destroyed: 'Bye! Your account was successfully cancelled. We hope to see you again soon.'
+ unlocks:
+ send_instructions: 'You will receive an email with instructions about how to unlock your account in a few minutes.'
+ unlocked: 'Your account was successfully unlocked. You are now signed in.'
+ mailer:
+ confirmation_instructions:
+ subject: 'Confirmation instructions'
+ reset_password_instructions:
+ subject: 'Reset password instructions'
+ unlock_instructions:
+ subject: 'Unlock Instructions'
View
5 episode-236/todo/config/locales/en.yml
@@ -0,0 +1,5 @@
+# Sample localization file for English. Add more files in this directory for other locales.
+# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+
+en:
+ hello: "Hello world"
View
8 episode-236/todo/config/routes.rb
@@ -0,0 +1,8 @@
+Todo::Application.routes.draw do
+ match '/auth/:provider/callback' => 'authentications#create'
+ devise_for :users, :controllers => {:registrations => 'registrations'}
+ resources :projects
+ resources :tasks
+ resources :authentications
+ root :to => "projects#index"
+end
View
12 episode-236/todo/db/migrate/20100927035419_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-236/todo/db/migrate/20100927035455_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.datetime :completed_at
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :tasks
+ end
+end
View
26 episode-236/todo/db/migrate/20100927035705_devise_create_users.rb
@@ -0,0 +1,26 @@
+class DeviseCreateUsers < ActiveRecord::Migration
+ def self.up
+ create_table(:users) do |t|
+ t.database_authenticatable :null => false
+ t.recoverable
+ t.rememberable
+ t.trackable
+
+ # t.confirmable
+ # t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
+ # t.token_authenticatable
+
+
+ t.timestamps
+ end
+
+ add_index :users, :email, :unique => true
+ add_index :users, :reset_password_token, :unique => true
+ # add_index :users, :confirmation_token, :unique => true
+ # add_index :users, :unlock_token, :unique => true
+ end
+
+ def self.down
+ drop_table :users
+ end
+end
View
14 episode-236/todo/db/migrate/20101011050048_create_authentications.rb
@@ -0,0 +1,14 @@
+class CreateAuthentications < ActiveRecord::Migration
+ def self.up
+ create_table :authentications do |t|
+ t.integer :user_id
+ t.string :provider
+ t.string :uid
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :authentications
+ end
+end
View
56 episode-236/todo/db/schema.rb
@@ -0,0 +1,56 @@
+# 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 => 20101011050048) do
+
+ create_table "authentications", :force => true do |t|
+ t.integer "user_id"
+ t.string "provider"
+ t.string "uid"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "projects", :force => true do |t|
+ t.string "name"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "tasks", :force => true do |t|
+ t.integer "project_id"
+ t.string "name"
+ t.datetime "completed_at"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "users", :force => true do |t|
+ t.string "email", :default => "", :null => false
+ t.string "encrypted_password", :limit => 128, :default => "", :null => false
+ t.string "password_salt", :default => "", :null => false
+ t.string "reset_password_token"
+ t.string "remember_token"
+ t.datetime "remember_created_at"
+ t.integer "sign_in_count", :default => 0
+ t.datetime "current_sign_in_at"
+ t.datetime "last_sign_in_at"
+ t.string "current_sign_in_ip"
+ t.string "last_sign_in_ip"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ add_index "users", ["email"], :name => "index_users_on_email", :unique => true
+ add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
+
+end
View
7 episode-236/todo/db/seeds.rb
@@ -0,0 +1,7 @@
+# This file should contain all the record creation needed to seed the database with its default values.
+# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
+#
+# Examples:
+#
+# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
+# Mayor.create(:name => 'Daley', :city => cities.first)
View
2  episode-236/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
0  episode-236/todo/lib/tasks/.gitkeep
No changes.
View
26 episode-236/todo/public/404.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The page you were looking for doesn't exist (404)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/404.html -->
+ <div class="dialog">
+ <h1>The page you were looking for doesn't exist.</h1>
+ <p>You may have mistyped the address or the page may have moved.</p>
+ </div>
+</body>
+</html>
View
26 episode-236/todo/public/422.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The change you wanted was rejected (422)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/422.html -->
+ <div class="dialog">
+ <h1>The change you wanted was rejected.</h1>
+ <p>Maybe you tried to change something you didn't have access to.</p>
+ </div>
+</body>
+</html>
View
26 episode-236/todo/public/500.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>We're sorry, but something went wrong (500)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/500.html -->
+ <div class="dialog">
+ <h1>We're sorry, but something went wrong.</h1>
+ <p>We've been notified about this issue and we'll take a look at it shortly.</p>
+ </div>
+</body>
+</html>
View
0  episode-236/todo/public/favicon.ico
No changes.
View
BIN  episode-236/todo/public/images/facebook_64.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  episode-236/todo/public/images/google_apps_64.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  episode-236/todo/public/images/open_id_32.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  episode-236/todo/public/images/open_id_64.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  episode-236/todo/public/images/rails.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  episode-236/todo/public/images/twitter_32.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  episode-236/todo/public/images/twitter_64.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
2  episode-236/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
965 episode-236/todo/public/javascripts/controls.js
@@ -0,0 +1,965 @@
+// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
+// Contributors:
+// Richard Livsey
+// Rahul Bhargava
+// Rob Wills
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// Autocompleter.Base handles all the autocompletion functionality
+// that's independent of the data source for autocompletion. This
+// includes drawing the autocompletion menu, observing keyboard
+// and mouse events, and similar.
+//
+// Specific autocompleters need to provide, at the very least,
+// a getUpdatedChoices function that will be invoked every time
+// the text inside the monitored textbox changes. This method
+// should get the text for which to provide autocompletion by
+// invoking this.getToken(), NOT by directly accessing
+// this.element.value. This is to allow incremental tokenized
+// autocompletion. Specific auto-completion logic (AJAX, etc)
+// belongs in getUpdatedChoices.
+//
+// Tokenized incremental autocompletion is enabled automatically
+// when an autocompleter is instantiated with the 'tokens' option
+// in the options parameter, e.g.:
+// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
+// will incrementally autocomplete with a comma as the token.
+// Additionally, ',' in the above example can be replaced with
+// a token array, e.g. { tokens: [',', '\n'] } which
+// enables autocompletion on multiple tokens. This is most
+// useful when one of the tokens is \n (a newline), as it
+// allows smart autocompletion after linebreaks.
+
+if(typeof Effect == 'undefined')
+ throw("controls.js requires including script.aculo.us' effects.js library");
+
+var Autocompleter = { };
+Autocompleter.Base = Class.create({
+ baseInitialize: function(element, update, options) {
+ element = $(element);
+ this.element = element;
+ this.update = $(update);
+ this.hasFocus = false;
+ this.changed = false;
+ this.active = false;
+ this.index = 0;
+ this.entryCount = 0;
+ this.oldElementValue = this.element.value;
+
+ if(this.setOptions)
+ this.setOptions(options);
+ else
+ this.options = options || { };
+
+ this.options.paramName = this.options.paramName || this.element.name;
+ this.options.tokens = this.options.tokens || [];
+ this.options.frequency = this.options.frequency || 0.4;
+ this.options.minChars = this.options.minChars || 1;
+ this.options.onShow = this.options.onShow ||
+ function(element, update){
+ if(!update.style.position || update.style.position=='absolute') {
+ update.style.position = 'absolute';
+ Position.clone(element, update, {
+ setHeight: false,
+ offsetTop: element.offsetHeight
+ });
+ }
+ Effect.Appear(update,{duration:0.15});
+ };
+ this.options.onHide = this.options.onHide ||
+ function(element, update){ new Effect.Fade(update,{duration:0.15}) };
+
+ if(typeof(this.options.tokens) == 'string')
+ this.options.tokens = new Array(this.options.tokens);
+ // Force carriage returns as token delimiters anyway
+ if (!this.options.tokens.include('\n'))
+ this.options.tokens.push('\n');
+
+ this.observer = null;
+
+ this.element.setAttribute('autocomplete','off');
+
+ Element.hide(this.update);
+
+ Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
+ Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
+ },
+
+ show: function() {
+ if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
+ if(!this.iefix &&
+ (Prototype.Browser.IE) &&
+ (Element.getStyle(this.update, 'position')=='absolute')) {
+ new Insertion.After(this.update,
+ '<iframe id="' + this.update.id + '_iefix" '+
+ 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
+ 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
+ this.iefix = $(this.update.id+'_iefix');
+ }
+ if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
+ },
+
+ fixIEOverlapping: function() {
+ Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
+ this.iefix.style.zIndex = 1;
+ this.update.style.zIndex = 2;
+ Element.show(this.iefix);
+ },
+
+ hide: function() {
+ this.stopIndicator();
+ if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
+ if(this.iefix) Element.hide(this.iefix);
+ },
+
+ startIndicator: function() {
+ if(this.options.indicator) Element.show(this.options.indicator);
+ },
+
+ stopIndicator: function() {
+ if(this.options.indicator) Element.hide(this.options.indicator);
+ },
+
+ onKeyPress: function(event) {
+ if(this.active)
+ switch(event.keyCode) {
+ case Event.KEY_TAB:
+ case Event.KEY_RETURN:
+ this.selectEntry();
+ Event.stop(event);
+ case Event.KEY_ESC:
+ this.hide();
+ this.active = false;
+ Event.stop(event);
+ return;
+ case Event.KEY_LEFT:
+ case Event.KEY_RIGHT:
+ return;
+ case Event.KEY_UP:
+ this.markPrevious();
+ this.render();
+ Event.stop(event);
+ return;
+ case Event.KEY_DOWN:
+ this.markNext();
+ this.render();
+ Event.stop(event);
+ return;
+ }
+ else
+ if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
+ (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
+
+ this.changed = true;
+ this.hasFocus = true;
+
+ if(this.observer) clearTimeout(this.observer);
+ this.observer =
+ setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
+ },
+
+ activate: function() {
+ this.changed = false;
+ this.hasFocus = true;
+ this.getUpdatedChoices();
+ },
+
+ onHover: function(event) {
+ var element = Event.findElement(event, 'LI');
+ if(this.index != element.autocompleteIndex)
+ {
+ this.index = element.autocompleteIndex;
+ this.render();
+ }
+ Event.stop(event);
+ },
+
+ onClick: function(event) {
+ var element = Event.findElement(event, 'LI');
+ this.index = element.autocompleteIndex;
+ this.selectEntry();
+ this.hide();
+ },
+
+ onBlur: function(event) {
+ // needed to make click events working
+ setTimeout(this.hide.bind(this), 250);
+ this.hasFocus = false;
+ this.active = false;
+ },
+
+ render: function() {
+ if(this.entryCount > 0) {
+ for (var i = 0; i < this.entryCount; i++)
+ this.index==i ?
+ Element.addClassName(this.getEntry(i),"selected") :
+ Element.removeClassName(this.getEntry(i),"selected");
+ if(this.hasFocus) {
+ this.show();
+ this.active = true;
+ }
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ },
+
+ markPrevious: function() {
+ if(this.index > 0) this.index--;
+ else this.index = this.entryCount-1;
+ this.getEntry(this.index).scrollIntoView(true);
+ },
+
+ markNext: function() {
+ if(this.index < this.entryCount-1) this.index++;
+ else this.index = 0;
+ this.getEntry(this.index).scrollIntoView(false);
+ },
+
+ getEntry: function(index) {
+ return this.update.firstChild.childNodes[index];
+ },
+
+ getCurrentEntry: function() {
+ return this.getEntry(this.index);
+ },
+
+ selectEntry: function() {
+ this.active = false;
+ this.updateElement(this.getCurrentEntry());
+ },
+
+ updateElement: function(selectedElement) {
+ if (this.options.updateElement) {
+ this.options.updateElement(selectedElement);
+ return;
+ }
+ var value = '';
+ if (this.options.select) {
+ var nodes = $(selectedElement).select('.' + this.options.select) || [];
+ if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
+ } else
+ value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
+
+ var bounds = this.getTokenBounds();
+ if (bounds[0] != -1) {
+ var newValue = this.element.value.substr(0, bounds[0]);
+ var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
+ if (whitespace)
+ newValue += whitespace[0];
+ this.element.value = newValue + value + this.element.value.substr(bounds[1]);
+ } else {
+ this.element.value = value;
+ }
+ this.oldElementValue = this.element.value;
+ this.element.focus();
+
+ if (this.options.afterUpdateElement)
+ this.options.afterUpdateElement(this.element, selectedElement);
+ },
+
+ updateChoices: function(choices) {
+ if(!this.changed && this.hasFocus) {
+ this.update.innerHTML = choices;
+ Element.cleanWhitespace(this.update);
+ Element.cleanWhitespace(this.update.down());
+
+ if(this.update.firstChild && this.update.down().childNodes) {
+ this.entryCount =
+ this.update.down().childNodes.length;
+ for (var i = 0; i < this.entryCount; i++) {
+ var entry = this.getEntry(i);
+ entry.autocompleteIndex = i;
+ this.addObservers(entry);
+ }
+ } else {
+ this.entryCount = 0;
+ }
+
+ this.stopIndicator();
+ this.index = 0;
+
+ if(this.entryCount==1 && this.options.autoSelect) {
+ this.selectEntry();
+ this.hide();
+ } else {
+ this.render();
+ }
+ }
+ },
+
+ addObservers: function(element) {
+ Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
+ Event.observe(element, "click", this.onClick.bindAsEventListener(this));
+ },
+
+ onObserverEvent: function() {
+ this.changed = false;
+ this.tokenBounds = null;
+ if(this.getToken().length>=this.options.minChars) {
+ this.getUpdatedChoices();
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ this.oldElementValue = this.element.value;
+ },
+
+ getToken: function() {
+ var bounds = this.getTokenBounds();
+ return this.element.value.substring(bounds[0], bounds[1]).strip();
+ },
+
+ getTokenBounds: function() {
+ if (null != this.tokenBounds) return this.tokenBounds;
+ var value = this.element.value;
+ if (value.strip().empty()) return [-1, 0];
+ var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
+ var offset = (diff == this.oldElementValue.length ? 1 : 0);
+ var prevTokenPos = -1, nextTokenPos = value.length;
+ var tp;
+ for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
+ tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
+ if (tp > prevTokenPos) prevTokenPos = tp;
+ tp = value.indexOf(this.options.tokens[index], diff + offset);
+ if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
+ }
+ return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
+ }
+});
+
+Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
+ var boundary = Math.min(newS.length, oldS.length);
+ for (var index = 0; index < boundary; ++index)
+ if (newS[index] != oldS[index])
+ return index;
+ return boundary;
+};
+
+Ajax.Autocompleter = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, url, options) {
+ this.baseInitialize(element, update, options);
+ this.options.asynchronous = true;
+ this.options.onComplete = this.onComplete.bind(this);
+ this.options.defaultParams = this.options.parameters || null;
+ this.url = url;
+ },
+
+ getUpdatedChoices: function() {
+ this.startIndicator();
+
+ var entry = encodeURIComponent(this.options.paramName) + '=' +
+ encodeURIComponent(this.getToken());
+
+ this.options.parameters = this.options.callback ?
+ this.options.callback(this.element, entry) : entry;
+
+ if(this.options.defaultParams)
+ this.options.parameters += '&' + this.options.defaultParams;
+
+ new Ajax.Request(this.url, this.