Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

automatic import from ryanb/railscasts-episodes

  • Loading branch information...
commit 05bbae719c22eef30ddd32b60df204c3611d3c1d 0 parents
@gilesbowkett gilesbowkett authored
Showing with 8,933 additions and 0 deletions.
  1. +9 −0 README
  2. +3 −0  blog/.gitignore
  3. +4 −0 blog/README
  4. +10 −0 blog/Rakefile
  5. +16 −0 blog/app/controllers/application_controller.rb
  6. +42 −0 blog/app/controllers/articles_controller.rb
  7. +34 −0 blog/app/controllers/comments_controller.rb
  8. +22 −0 blog/app/controllers/user_sessions_controller.rb
  9. +15 −0 blog/app/controllers/users_controller.rb
  10. +3 −0  blog/app/helpers/application_helper.rb
  11. +2 −0  blog/app/helpers/articles_helper.rb
  12. +2 −0  blog/app/helpers/comments_helper.rb
  13. +23 −0 blog/app/helpers/layout_helper.rb
  14. +2 −0  blog/app/helpers/user_sessions_helper.rb
  15. +2 −0  blog/app/helpers/users_helper.rb
  16. +5 −0 blog/app/models/article.rb
  17. +4 −0 blog/app/models/assignment.rb
  18. +5 −0 blog/app/models/comment.rb
  19. +4 −0 blog/app/models/role.rb
  20. +21 −0 blog/app/models/user.rb
  21. +2 −0  blog/app/models/user_session.rb
  22. +16 −0 blog/app/views/articles/_form.html.erb
  23. +8 −0 blog/app/views/articles/edit.html.erb
  24. +16 −0 blog/app/views/articles/index.html.erb
  25. +5 −0 blog/app/views/articles/new.html.erb
  26. +42 −0 blog/app/views/articles/show.html.erb
  27. +17 −0 blog/app/views/comments/_form.html.erb
  28. +4 −0 blog/app/views/comments/edit.html.erb
  29. +4 −0 blog/app/views/comments/new.html.erb
  30. +31 −0 blog/app/views/layouts/application.html.erb
  31. +16 −0 blog/app/views/user_sessions/new.html.erb
  32. +32 −0 blog/app/views/users/new.html.erb
  33. +26 −0 blog/config/authorization_rules.rb
  34. +110 −0 blog/config/boot.rb
  35. +19 −0 blog/config/database.yml
  36. +69 −0 blog/config/environment.rb
  37. +17 −0 blog/config/environments/development.rb
  38. +22 −0 blog/config/environments/production.rb
  39. +22 −0 blog/config/environments/test.rb
  40. +10 −0 blog/config/initializers/inflections.rb
  41. +5 −0 blog/config/initializers/mime_types.rb
  42. +15 −0 blog/config/initializers/new_rails_defaults.rb
  43. +11 −0 blog/config/routes.rb
  44. +14 −0 blog/db/migrate/20080719200447_create_articles.rb
  45. +15 −0 blog/db/migrate/20080719201435_create_comments.rb
  46. +16 −0 blog/db/migrate/20091116005037_create_users.rb
  47. +12 −0 blog/db/migrate/20091116011510_create_roles.rb
  48. +14 −0 blog/db/migrate/20091116072645_create_assignments.rb
  49. +11 −0 blog/db/migrate/20091116073210_add_user_to_articles.rb
  50. +9 −0 blog/db/migrate/20091123010658_add_role_to_users.rb
  51. +9 −0 blog/db/migrate/20091123013022_add_roles_mask_to_users.rb
  52. +58 −0 blog/db/schema.rb
  53. +2 −0  blog/doc/README_FOR_APP
  54. +55 −0 blog/lib/authentication.rb
  55. +2 −0  blog/lib/tasks/application.rake
  56. +30 −0 blog/public/404.html
  57. +30 −0 blog/public/422.html
  58. +30 −0 blog/public/500.html
  59. +10 −0 blog/public/dispatch.cgi
  60. +24 −0 blog/public/dispatch.fcgi
  61. +10 −0 blog/public/dispatch.rb
  62. 0  blog/public/favicon.ico
  63. +2 −0  blog/public/javascripts/application.js
  64. +963 −0 blog/public/javascripts/controls.js
  65. +973 −0 blog/public/javascripts/dragdrop.js
  66. +1,128 −0 blog/public/javascripts/effects.js
  67. +4,320 −0 blog/public/javascripts/prototype.js
  68. +5 −0 blog/public/robots.txt
  69. +118 −0 blog/public/stylesheets/application.css
  70. +3 −0  blog/script/about
  71. +3 −0  blog/script/console
  72. +3 −0  blog/script/dbconsole
  73. +3 −0  blog/script/destroy
  74. +3 −0  blog/script/generate
  75. +3 −0  blog/script/performance/benchmarker
  76. +3 −0  blog/script/performance/profiler
  77. +3 −0  blog/script/performance/request
  78. +3 −0  blog/script/plugin
  79. +3 −0  blog/script/process/inspector
  80. +3 −0  blog/script/process/reaper
  81. +3 −0  blog/script/process/spawner
  82. +3 −0  blog/script/runner
  83. +3 −0  blog/script/server
  84. +17 −0 blog/test/fixtures/articles.yml
  85. +9 −0 blog/test/fixtures/assignments.yml
  86. +21 −0 blog/test/fixtures/comments.yml
  87. +11 −0 blog/test/fixtures/roles.yml
  88. +14 −0 blog/test/fixtures/users.yml
  89. +54 −0 blog/test/functional/articles_controller_test.rb
  90. +44 −0 blog/test/functional/comments_controller_test.rb
  91. +20 −0 blog/test/functional/user_sessions_controller_test.rb
  92. +20 −0 blog/test/functional/users_controller_test.rb
  93. +38 −0 blog/test/test_helper.rb
  94. +8 −0 blog/test/unit/article_test.rb
  95. +8 −0 blog/test/unit/assignment_test.rb
  96. +8 −0 blog/test/unit/comment_test.rb
  97. +8 −0 blog/test/unit/role_test.rb
  98. +4 −0 blog/test/unit/user_test.rb
9 README
@@ -0,0 +1,9 @@
+Railscasts Episode #189: Embedded Association
+
+http://railscasts.com/episodes/189
+
+Commands
+
+ script/generate migration add_role_to_users role:string
+ script/generate migration add_roles_mask_to_users roles_mask:integer
+ rake db:migrate
3  blog/.gitignore
@@ -0,0 +1,3 @@
+tmp/*
+log/*
+*.sqlite3
4 blog/README
@@ -0,0 +1,4 @@
+Railscasts Example Blog App
+--
+
+To setup the app, just run `rake setup`.
10 blog/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'
16 blog/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
+ protect_from_forgery
+ before_filter { |c| Authorization.current_user = c.current_user }
+
+ protected
+
+ def permission_denied
+ flash[:error] = "Sorry, you are not allowed to access that page."
+ redirect_to root_url
+ end
+end
42 blog/app/controllers/articles_controller.rb
@@ -0,0 +1,42 @@
+class ArticlesController < ApplicationController
+ filter_resource_access
+
+ def index
+ @articles = Article.find(:all)
+ end
+
+ def show
+ @comment = Comment.new(:article => @article)
+ end
+
+ def new
+ end
+
+ def create
+ @article.user = current_user
+ if @article.save
+ flash[:notice] = "Successfully created article."
+ redirect_to @article
+ else
+ render :action => 'new'
+ end
+ end
+
+ def edit
+ end
+
+ def update
+ if @article.update_attributes(params[:article])
+ flash[:notice] = "Successfully updated article."
+ redirect_to @article
+ else
+ render :action => 'edit'
+ end
+ end
+
+ def destroy
+ @article.destroy
+ flash[:notice] = "Successfully destroyed article."
+ redirect_to articles_url
+ end
+end
34 blog/app/controllers/comments_controller.rb
@@ -0,0 +1,34 @@
+class CommentsController < ApplicationController
+ filter_resource_access
+
+ def new
+ end
+
+ def create
+ @comment.user = current_user
+ if @comment.save
+ flash[:notice] = "Successfully created comment."
+ redirect_to article_url(@comment.article_id)
+ else
+ render :action => 'new'
+ end
+ end
+
+ def edit
+ end
+
+ def update
+ if @comment.update_attributes(params[:comment])
+ flash[:notice] = "Successfully updated comment."
+ redirect_to article_url(@comment.article_id)
+ else
+ render :action => 'edit'
+ end
+ end
+
+ def destroy
+ @comment.destroy
+ flash[:notice] = "Successfully destroyed comment."
+ redirect_to article_url(@comment.article_id)
+ end
+end
22 blog/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
15 blog/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
3  blog/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
2  blog/app/helpers/articles_helper.rb
@@ -0,0 +1,2 @@
+module ArticlesHelper
+end
2  blog/app/helpers/comments_helper.rb
@@ -0,0 +1,2 @@
+module CommentsHelper
+end
23 blog/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
2  blog/app/helpers/user_sessions_helper.rb
@@ -0,0 +1,2 @@
+module UserSessionsHelper
+end
2  blog/app/helpers/users_helper.rb
@@ -0,0 +1,2 @@
+module UsersHelper
+end
5 blog/app/models/article.rb
@@ -0,0 +1,5 @@
+class Article < ActiveRecord::Base
+ has_many :comments, :dependent => :destroy
+ validates_presence_of :name, :content
+ belongs_to :user
+end
4 blog/app/models/assignment.rb
@@ -0,0 +1,4 @@
+class Assignment < ActiveRecord::Base
+ belongs_to :user
+ belongs_to :role
+end
5 blog/app/models/comment.rb
@@ -0,0 +1,5 @@
+class Comment < ActiveRecord::Base
+ belongs_to :article
+ belongs_to :user
+ validates_presence_of :author_name, :content
+end
4 blog/app/models/role.rb
@@ -0,0 +1,4 @@
+class Role < ActiveRecord::Base
+ has_many :assignments
+ has_many :users, :through => :assignments
+end
21 blog/app/models/user.rb
@@ -0,0 +1,21 @@
+class User < ActiveRecord::Base
+ acts_as_authentic
+ has_many :articles
+ has_many :comments
+
+ named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0"} }
+
+ ROLES = %w[admin moderator author]
+
+ def roles=(roles)
+ self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
+ end
+
+ def roles
+ ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }
+ end
+
+ def role_symbols
+ roles.map(&:to_sym)
+ end
+end
2  blog/app/models/user_session.rb
@@ -0,0 +1,2 @@
+class UserSession < Authlogic::Session::Base
+end
16 blog/app/views/articles/_form.html.erb
@@ -0,0 +1,16 @@
+<%= error_messages_for :article %>
+<% form_for @article do |f| %>
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.label :content %><br />
+ <%= f.text_area :content %>
+ </p>
+ <p>
+ <%= f.label :author_name %><br />
+ <%= f.text_field :author_name %>
+ </p>
+ <p><%= f.submit "Submit" %></p>
+<% end %>
8 blog/app/views/articles/edit.html.erb
@@ -0,0 +1,8 @@
+<% title "Edit Article" %>
+
+<%= render :partial => 'form' %>
+
+<p>
+ <%= link_to "Show", @article %> |
+ <%= link_to "View All", articles_path %>
+</p>
16 blog/app/views/articles/index.html.erb
@@ -0,0 +1,16 @@
+<% title "Articles" %>
+
+<div id="articles">
+<% for article in @articles %>
+ <h2>
+ <%= link_to h(article.name), article %>
+ <span class="comments">(<%= pluralize(article.comments.size, 'comment') %>)</span>
+ </h2>
+ <div class="author">from <%=h article.author_name %> on <%= article.created_at.strftime('%b %d, %Y') %></div>
+ <div class="content"><%= simple_format(article.content) %></div>
+<% end %>
+</div>
+
+<% if permitted_to? :create, Article.new %>
+ <p><%= link_to "New Article", new_article_path %></p>
+<% end %>
5 blog/app/views/articles/new.html.erb
@@ -0,0 +1,5 @@
+<% title "New Article" %>
+
+<%= render :partial => 'form' %>
+
+<p><%= link_to "Back to List", articles_path %></p>
42 blog/app/views/articles/show.html.erb
@@ -0,0 +1,42 @@
+<% title @article.name %>
+
+<p class="author"><em>from <%=h @article.author_name %></em></p>
+
+<%= simple_format @article.content %>
+
+<p>
+ <% if permitted_to? :edit, @article %>
+ <%= link_to "Edit", edit_article_path(@article) %> |
+ <% end %>
+ <% if permitted_to? :destroy, @article %>
+ <%= link_to "Destroy", @article, :method => :delete, :confirm => "Are you sure?" %> |
+ <% end %>
+ <%= link_to "Back to Articles", articles_path %>
+</p>
+
+<% unless @article.comments.empty? %>
+ <h2><%= pluralize(@article.comments.size, 'comment') %></h2>
+
+ <div id="comments">
+ <% for comment in @article.comments %>
+ <div class="comment">
+ <strong><%= link_to_unless comment.site_url.blank?, h(comment.author_name), h(comment.site_url) %></strong>
+ <em>on <%= comment.created_at.strftime('%b %d, %Y at %H:%M') %></em>
+ <%=simple_format comment.content %>
+ <p>
+ <% if permitted_to? :edit, comment %>
+ <%= link_to "Edit", edit_comment_path(comment) %>
+ <% end %>
+ <% if permitted_to? :destroy, comment %>
+ | <%= link_to "Destroy", comment, :method => :delete, :confirm => "Are you sure?" %>
+ <% end %>
+ </p>
+ </div>
+ <% end %>
+ </div>
+<% end %>
+
+<% if permitted_to? :create, @comment %>
+ <h3>Add your comment:</h3>
+ <%= render :partial => 'comments/form' %>
+<% end %>
17 blog/app/views/comments/_form.html.erb
@@ -0,0 +1,17 @@
+<%= error_messages_for :comment %>
+<% form_for @comment do |f| %>
+ <%= f.hidden_field :article_id %>
+ <p>
+ <%= f.label :author_name, 'Name' %><br />
+ <%= f.text_field :author_name %>
+ </p>
+ <p>
+ <%= f.label :site_url, 'Website URL' %><br />
+ <%= f.text_field :site_url %>
+ </p>
+ <p>
+ <%= f.label :content, 'Comment' %><br />
+ <%= f.text_area :content, :rows => '12', :cols => 35 %>
+ </p>
+ <p><%= f.submit "Submit" %></p>
+<% end %>
4 blog/app/views/comments/edit.html.erb
@@ -0,0 +1,4 @@
+<% title "Edit Comment" %>
+
+<%= render :partial => 'form' %>
+
4 blog/app/views/comments/new.html.erb
@@ -0,0 +1,4 @@
+<% title "New Comment" %>
+
+<%= render :partial => 'form' %>
+
31 blog/app/views/layouts/application.html.erb
@@ -0,0 +1,31 @@
+<!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_status">
+ <% 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>
16 blog/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 %>
32 blog/app/views/users/new.html.erb
@@ -0,0 +1,32 @@
+<% 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.label :roles %><br />
+ <% for role in User::ROLES %>
+ <%= check_box_tag "user[roles][]", role, @user.roles.include?(role) %>
+ <%=h role.humanize %><br />
+ <% end %>
+ <%= hidden_field_tag "user[roles][]", "" %>
+ </p>
+ <p><%= f.submit "Sign up" %></p>
+<% end %>
26 blog/config/authorization_rules.rb
@@ -0,0 +1,26 @@
+authorization do
+ role :admin do
+ has_permission_on [:articles, :comments], :to => [:index, :show, :new, :create, :edit, :update, :destroy]
+ end
+
+ role :guest do
+ has_permission_on :articles, :to => [:index, :show]
+ has_permission_on :comments, :to => [:new, :create]
+ has_permission_on :comments, :to => [:edit, :update] do
+ if_attribute :user => is { user }
+ end
+ end
+
+ role :moderator do
+ includes :guest
+ has_permission_on :comments, :to => [:edit, :update]
+ end
+
+ role :author do
+ includes :guest
+ has_permission_on :articles, :to => [:new, :create]
+ has_permission_on :articles, :to => [:edit, :update] do
+ if_attribute :user => is { user }
+ end
+ end
+end
110 blog/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!
19 blog/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
69 blog/config/environment.rb
@@ -0,0 +1,69 @@
+# Be sure to restart your server when you modify this file
+
+# Uncomment below to force Rails into production mode when
+# you don't control web/app server and can't set it the proper way
+# ENV['RAILS_ENV'] ||= 'production'
+
+# Specifies gem version of Rails to use when vendor/rails is not present
+RAILS_GEM_VERSION = '2.3.4' 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"
+ config.gem "declarative_authorization", :source => "http://gemcutter.org"
+
+ # 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 => '_blog_session',
+ :secret => 'f3f57b71ef9345ffccd0c4e841d8e74bb2e7d2ef692a5303bb455fea0667a62d30458d17f95766b12906aa6c2a3c29d584a55dd18426ffc04610be49956a51af'
+ }
+
+ # 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
17 blog/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
22 blog/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
22 blog/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
10 blog/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
5 blog/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
15 blog/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
11 blog/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 :articles, :comments
+ map.root :articles
+end
14 blog/db/migrate/20080719200447_create_articles.rb
@@ -0,0 +1,14 @@
+class CreateArticles < ActiveRecord::Migration
+ def self.up
+ create_table :articles do |t|
+ t.string :name
+ t.text :content
+ t.string :author_name
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :articles
+ end
+end
15 blog/db/migrate/20080719201435_create_comments.rb
@@ -0,0 +1,15 @@
+class CreateComments < ActiveRecord::Migration
+ def self.up
+ create_table :comments do |t|
+ t.integer :article_id
+ t.string :author_name
+ t.string :site_url
+ t.text :content
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :comments
+ end
+end
16 blog/db/migrate/20091116005037_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
12 blog/db/migrate/20091116011510_create_roles.rb
@@ -0,0 +1,12 @@
+class CreateRoles < ActiveRecord::Migration
+ def self.up
+ create_table :roles do |t|
+ t.string :name
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :roles
+ end
+end
14 blog/db/migrate/20091116072645_create_assignments.rb
@@ -0,0 +1,14 @@
+class CreateAssignments < ActiveRecord::Migration
+ def self.up
+ create_table :assignments do |t|
+ t.integer :user_id
+ t.integer :role_id
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :assignments
+ end
+end
11 blog/db/migrate/20091116073210_add_user_to_articles.rb
@@ -0,0 +1,11 @@
+class AddUserToArticles < ActiveRecord::Migration
+ def self.up
+ add_column :articles, :user_id, :integer
+ add_column :comments, :user_id, :integer
+ end
+
+ def self.down
+ remove_column :comments, :user_id
+ remove_column :articles, :user_id
+ end
+end
9 blog/db/migrate/20091123010658_add_role_to_users.rb
@@ -0,0 +1,9 @@
+class AddRoleToUsers < ActiveRecord::Migration
+ def self.up
+ add_column :users, :role, :string
+ end
+
+ def self.down
+ remove_column :users, :role
+ end
+end
9 blog/db/migrate/20091123013022_add_roles_mask_to_users.rb
@@ -0,0 +1,9 @@
+class AddRolesMaskToUsers < ActiveRecord::Migration
+ def self.up
+ add_column :users, :roles_mask, :integer
+ end
+
+ def self.down
+ remove_column :users, :roles_mask
+ end
+end
58 blog/db/schema.rb
@@ -0,0 +1,58 @@
+# 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 => 20091123013022) do
+
+ create_table "articles", :force => true do |t|
+ t.string "name"
+ t.text "content"
+ t.string "author_name"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ t.integer "user_id"
+ end
+
+ create_table "assignments", :force => true do |t|
+ t.integer "user_id"
+ t.integer "role_id"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "comments", :force => true do |t|
+ t.integer "article_id"
+ t.string "author_name"
+ t.string "site_url"
+ t.text "content"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ t.integer "user_id"
+ end
+
+ create_table "roles", :force => true do |t|
+ t.string "name"
+ 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"
+ t.string "role"
+ t.integer "roles_mask"
+ end
+
+end
2  blog/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.
55 blog/lib/authentication.rb
@@ -0,0 +1,55 @@
+# 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
+ controller.filter_parameter_logging :password
+ 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
2  blog/lib/tasks/application.rake
@@ -0,0 +1,2 @@
+desc "Setup all for app"
+task :setup => ['db:migrate', 'db:fixtures:load']
30 blog/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>
30 blog/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>
30 blog/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>
10 blog/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
24 blog/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!
10 blog/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
0  blog/public/favicon.ico
No changes.
2  blog/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
963 blog/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);