Browse files

initial commit

  • Loading branch information...
0 parents commit 0a5acaebf98bafe9d0256407493bd55960e4ba51 @Draiken committed Jun 17, 2011
Showing with 10,528 additions and 0 deletions.
  1. BIN .README.rdoc.swp
  2. BIN .acts_as_recommended.gemspec.swp
  3. +6 −0 .gitignore
  4. +1 −0 .rvmrc
  5. +11 −0 Gemfile
  6. +111 −0 Gemfile.lock
  7. +20 −0 MIT-LICENSE
  8. +88 −0 README.rdoc
  9. +25 −0 Rakefile
  10. +15 −0 acts_as_recommended.gemspec
  11. +9 −0 app/models/recommendation.rb
  12. BIN lib/.acts_as_recommended.rb.swp
  13. +8 −0 lib/acts_as_recommended.rb
  14. BIN lib/acts_as_recommended/.engine.rb.swp
  15. BIN lib/acts_as_recommended/.model_extensions.rb.swp
  16. BIN lib/acts_as_recommended/.railtie.rb.swp
  17. +11 −0 lib/acts_as_recommended/engine.rb
  18. +90 −0 lib/acts_as_recommended/model_extensions.rb
  19. +26 −0 lib/generators/acts_as_recommended/recommendations_for/recommendations_for_generator.rb
  20. BIN ...acts_as_recommended/recommendations_for/templates/migrations/.add_recommendations_to_table.rb.swp
  21. +11 −0 ...tors/acts_as_recommended/recommendations_for/templates/migrations/add_recommendations_to_table.rb
  22. +8 −0 lib/generators/acts_as_recommended/tables/USAGE
  23. +26 −0 lib/generators/acts_as_recommended/tables/tables_generator.rb
  24. BIN lib/generators/acts_as_recommended/tables/templates/migrations/.create_recommendations.rb.swp
  25. +19 −0 lib/generators/acts_as_recommended/tables/templates/migrations/create_recommendations.rb
  26. BIN spec/.acts_as_recommended_spec.rb.swp
  27. BIN spec/.spec_helper.rb.swp
  28. +70 −0 spec/acts_as_recommended_spec.rb
  29. +7 −0 spec/dummy/Rakefile
  30. +3 −0 spec/dummy/app/controllers/application_controller.rb
  31. +83 −0 spec/dummy/app/controllers/posts_controller.rb
  32. +2 −0 spec/dummy/app/helpers/application_helper.rb
  33. +2 −0 spec/dummy/app/helpers/posts_helper.rb
  34. +2 −0 spec/dummy/app/models/post.rb
  35. +2 −0 spec/dummy/app/models/user.rb
  36. +14 −0 spec/dummy/app/views/layouts/application.html.erb
  37. +21 −0 spec/dummy/app/views/posts/_form.html.erb
  38. +6 −0 spec/dummy/app/views/posts/edit.html.erb
  39. +23 −0 spec/dummy/app/views/posts/index.html.erb
  40. +5 −0 spec/dummy/app/views/posts/new.html.erb
  41. +10 −0 spec/dummy/app/views/posts/show.html.erb
  42. +4 −0 spec/dummy/config.ru
  43. +45 −0 spec/dummy/config/application.rb
  44. +10 −0 spec/dummy/config/boot.rb
  45. +22 −0 spec/dummy/config/database.yml
  46. +5 −0 spec/dummy/config/environment.rb
  47. +26 −0 spec/dummy/config/environments/development.rb
  48. +49 −0 spec/dummy/config/environments/production.rb
  49. +35 −0 spec/dummy/config/environments/test.rb
  50. +7 −0 spec/dummy/config/initializers/backtrace_silencers.rb
  51. +10 −0 spec/dummy/config/initializers/inflections.rb
  52. +5 −0 spec/dummy/config/initializers/mime_types.rb
  53. +7 −0 spec/dummy/config/initializers/secret_token.rb
  54. +8 −0 spec/dummy/config/initializers/session_store.rb
  55. +5 −0 spec/dummy/config/locales/en.yml
  56. +60 −0 spec/dummy/config/routes.rb
  57. +13 −0 spec/dummy/db/migrate/20110617123838_create_posts.rb
  58. +13 −0 spec/dummy/db/migrate/20110617123848_create_users.rb
  59. +19 −0 spec/dummy/db/migrate/20110617125425_create_recommendations.rb
  60. +11 −0 spec/dummy/db/migrate/20110617125441_add_recommendations_to_posts.rb
  61. +26 −0 spec/dummy/public/404.html
  62. +26 −0 spec/dummy/public/422.html
  63. +26 −0 spec/dummy/public/500.html
  64. 0 spec/dummy/public/favicon.ico
  65. +2 −0 spec/dummy/public/javascripts/application.js
  66. +965 −0 spec/dummy/public/javascripts/controls.js
  67. +974 −0 spec/dummy/public/javascripts/dragdrop.js
  68. +1,123 −0 spec/dummy/public/javascripts/effects.js
  69. +6,001 −0 spec/dummy/public/javascripts/prototype.js
  70. +191 −0 spec/dummy/public/javascripts/rails.js
  71. 0 spec/dummy/public/stylesheets/.gitkeep
  72. +56 −0 spec/dummy/public/stylesheets/scaffold.css
  73. +6 −0 spec/dummy/script/rails
  74. BIN spec/integration/.navigation_spec.rb.swp
  75. +9 −0 spec/integration/navigation_spec.rb
  76. +34 −0 spec/spec_helper.rb
BIN .README.rdoc.swp
Binary file not shown.
BIN .acts_as_recommended.gemspec.swp
Binary file not shown.
6 .gitignore
@@ -0,0 +1,6 @@
+.bundle/
+log/*.log
+pkg/
+spec/dummy/db/*.sqlite3
+spec/dummy/log/*.log
+spec/dummy/tmp/
1 .rvmrc
@@ -0,0 +1 @@
+rvm use 1.8.7@acts_as_recommended
11 Gemfile
@@ -0,0 +1,11 @@
+source "http://rubygems.org"
+
+gem "rails", "3.0.9"
+gem "capybara", ">= 0.4.0"
+gem "sqlite3"
+
+gem "rspec-rails", ">= 2.0.0.beta"
+
+# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)
+# gem 'ruby-debug'
+# gem 'ruby-debug19'
111 Gemfile.lock
@@ -0,0 +1,111 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ abstract (1.0.0)
+ actionmailer (3.0.9)
+ actionpack (= 3.0.9)
+ mail (~> 2.2.19)
+ actionpack (3.0.9)
+ activemodel (= 3.0.9)
+ activesupport (= 3.0.9)
+ builder (~> 2.1.2)
+ erubis (~> 2.6.6)
+ i18n (~> 0.5.0)
+ rack (~> 1.2.1)
+ rack-mount (~> 0.6.14)
+ rack-test (~> 0.5.7)
+ tzinfo (~> 0.3.23)
+ activemodel (3.0.9)
+ activesupport (= 3.0.9)
+ builder (~> 2.1.2)
+ i18n (~> 0.5.0)
+ activerecord (3.0.9)
+ activemodel (= 3.0.9)
+ activesupport (= 3.0.9)
+ arel (~> 2.0.10)
+ tzinfo (~> 0.3.23)
+ activeresource (3.0.9)
+ activemodel (= 3.0.9)
+ activesupport (= 3.0.9)
+ activesupport (3.0.9)
+ arel (2.0.10)
+ builder (2.1.2)
+ capybara (1.0.0)
+ mime-types (>= 1.16)
+ nokogiri (>= 1.3.3)
+ rack (>= 1.0.0)
+ rack-test (>= 0.5.4)
+ selenium-webdriver (~> 0.2.0)
+ xpath (~> 0.1.4)
+ childprocess (0.1.9)
+ ffi (~> 1.0.6)
+ diff-lcs (1.1.2)
+ erubis (2.6.6)
+ abstract (>= 1.0.0)
+ ffi (1.0.9)
+ i18n (0.5.0)
+ json_pure (1.5.2)
+ mail (2.2.19)
+ activesupport (>= 2.3.6)
+ i18n (>= 0.4.0)
+ mime-types (~> 1.16)
+ treetop (~> 1.4.8)
+ mime-types (1.16)
+ nokogiri (1.4.5)
+ polyglot (0.3.1)
+ rack (1.2.3)
+ rack-mount (0.6.14)
+ rack (>= 1.0.0)
+ rack-test (0.5.7)
+ rack (>= 1.0)
+ rails (3.0.9)
+ actionmailer (= 3.0.9)
+ actionpack (= 3.0.9)
+ activerecord (= 3.0.9)
+ activeresource (= 3.0.9)
+ activesupport (= 3.0.9)
+ bundler (~> 1.0)
+ railties (= 3.0.9)
+ railties (3.0.9)
+ actionpack (= 3.0.9)
+ activesupport (= 3.0.9)
+ rake (>= 0.8.7)
+ rdoc (~> 3.4)
+ thor (~> 0.14.4)
+ rake (0.9.2)
+ rdoc (3.6.1)
+ rspec (2.6.0)
+ rspec-core (~> 2.6.0)
+ rspec-expectations (~> 2.6.0)
+ rspec-mocks (~> 2.6.0)
+ rspec-core (2.6.4)
+ rspec-expectations (2.6.0)
+ diff-lcs (~> 1.1.2)
+ rspec-mocks (2.6.0)
+ rspec-rails (2.6.1)
+ actionpack (~> 3.0)
+ activesupport (~> 3.0)
+ railties (~> 3.0)
+ rspec (~> 2.6.0)
+ rubyzip (0.9.4)
+ selenium-webdriver (0.2.1)
+ childprocess (>= 0.1.7)
+ ffi (>= 1.0.7)
+ json_pure
+ rubyzip
+ sqlite3 (1.3.3)
+ thor (0.14.6)
+ treetop (1.4.9)
+ polyglot (>= 0.3.1)
+ tzinfo (0.3.28)
+ xpath (0.1.4)
+ nokogiri (~> 1.3)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ capybara (>= 0.4.0)
+ rails (= 3.0.9)
+ rspec-rails (>= 2.0.0.beta)
+ sqlite3
20 MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright 2011 YOURNAME
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
88 README.rdoc
@@ -0,0 +1,88 @@
+= Acts as Recommended
+
+A simple rails 3 engine to add recommendation functionallity to your application
+
+== Installation
+
+Add to your *Gemfile*
+
+ gem 'acts_as_recommended'
+
+And just run
+
+ bundle
+
+== Usage
+
+First thing we need is the recommendation model himself
+and we have a generator that creates the model's tables
+
+ rails g acts_as_recommended:tables
+
+After that we can add the required fields for our models with
+another generator
+
+ rails g acts_as_recommended:recommendations_for Post
+
+This will add a migration adding the required fields to add
+recommendations to a certain model.
+
+Then all we simply add this line to our desired model
+
+ acts_as_recommended
+
+Now, we can run the migrations and we can already recommend whatever we want!
+
+ post = Post.first
+
+ bob = User.first
+ joe = User.last
+ mary = User.find(100)
+
+ post.recommend!( true, bob )
+ post.recommend!( 0, joe )
+ post.recommend!( true, mary )
+
+ # good minus bad recommendations
+ post.recommendations # 1
+
+ post.recommendations_count # 3
+
+ post.good_recommendations # 2
+ post.bad_recommendations # 1
+
+ post.good_recommendations_percent # 66.67
+ # pass a format optionally
+ post.bad_recommendations_percent( '%.1f' ) # 33.3
+
+ # check if user recommended
+ post.recommended_by?( bob ) # true
+ post.recommended_by?( mary ) # true
+
+ # get user's recommendation
+ post.get_recommendation_of( bob ) # true
+ post.get_recommendation_of( mary ) # false
+
+Note: users can only recommend once, a second recommendation will replace the latter
+
+== Customization
+
+By default the recommendation must be done by a User model
+you can customize that with a simple initializer like *config/initializers/recommendations.rb*
+
+ ActsAsRecommended.owner_model = :admin
+
+
+== Contribution
+
+Want to contribute? Fork, make it, ask for pull request!
+Found an issue? Use the issues tracker!
+
+== TODO
+
+Create a simple controller to create/alter recommendations and generators for customization!
+
+== Author
+
+Created and mantained by Luiz Felipe Garcia Pereira aka {*Draiken*}[http://github.com/Draiken]
+
25 Rakefile
@@ -0,0 +1,25 @@
+# encoding: UTF-8
+require 'rubygems'
+begin
+ require 'bundler/setup'
+rescue LoadError
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
+end
+
+require 'rake'
+require 'rake/rdoctask'
+
+require 'rspec/core'
+require 'rspec/core/rake_task'
+
+RSpec::Core::RakeTask.new(:spec)
+
+task :default => :spec
+
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'ActsAsRecommended'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README.rdoc')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
15 acts_as_recommended.gemspec
@@ -0,0 +1,15 @@
+Gem::Specification.new do |s|
+ s.name = "acts_as_recommended"
+ s.version = "0.1.0"
+ s.platform = Gem::Platform::RUBY
+
+ s.authors = [ "Luiz Felipe Garcia Pereira" ]
+ s.email = [ "luiz.felipe.gp@gmail.com" ]
+
+ s.summary = "Insert ActsAsRecommended summary."
+ s.description = "Insert ActsAsRecommended description."
+
+ s.add_dependency( 'rails', '~> 3.0' )
+
+ s.files = Dir["{app,lib,config}/**/*"] + ["MIT-LICENSE", "Rakefile", "Gemfile", "README.rdoc"]
+end
9 app/models/recommendation.rb
@@ -0,0 +1,9 @@
+class Recommendation < ActiveRecord::Base
+
+ belongs_to :owner, :class_name => ActsAsRecommended.owner_class
+ belongs_to :recommendable, :polymorphic => true
+
+ scope :of_item, lambda { |item| where('recommendable_id = ?', item.id).where('recommendable_type = ?', item.class.base_class.name.to_s) }
+ scope :owned_by, lambda { |owner| where('owner_id = ?', owner.id) }
+
+end
BIN lib/.acts_as_recommended.rb.swp
Binary file not shown.
8 lib/acts_as_recommended.rb
@@ -0,0 +1,8 @@
+module ActsAsRecommended
+
+ mattr_accessor :owner_class
+ @@owner_class = :user
+
+end
+
+require 'acts_as_recommended/engine'
BIN lib/acts_as_recommended/.engine.rb.swp
Binary file not shown.
BIN lib/acts_as_recommended/.model_extensions.rb.swp
Binary file not shown.
BIN lib/acts_as_recommended/.railtie.rb.swp
Binary file not shown.
11 lib/acts_as_recommended/engine.rb
@@ -0,0 +1,11 @@
+module ActsAsRecommended
+ class Engine < ::Rails::Engine
+ initializer :acts_as_recommended do |app|
+ ActiveSupport.on_load(:active_record) do
+ require File.join(File.dirname(__FILE__), 'model_extensions')
+ ::ActiveRecord::Base.send :include, ActsAsRecommended::ModelExtensions
+ end
+ end
+
+ end
+end
90 lib/acts_as_recommended/model_extensions.rb
@@ -0,0 +1,90 @@
+module ActsAsRecommended
+ module ModelExtensions
+
+ def self.included(base)
+ # :nodoc:
+ base.extend(ClassMethods)
+ end
+
+ module ClassMethods
+
+ def acts_as_recommended(*args)
+ return if self.included_modules.include?(ActsAsRecommended::ModelExtensions::ActsAsRecommendedMethods)
+ send :include, ActsAsRecommended::ModelExtensions::ActsAsRecommendedMethods
+ end
+
+ end
+
+ # Métodos utilizados para incrementar e decrementar os contadores
+ # de contribuição.
+ #
+ module ActsAsRecommendedMethods
+
+ def recommend!(recommendation, owner)
+ raise "Recommendation cannot be nil" if recommendation.nil?
+
+ # either a 1/0 or a true/false
+ recommendation = _normalize_recommendation(recommendation)
+
+ # find last recomendation of this item
+ # from this user or create a new one
+ new_recommendation = _new_or_last_recommendation_for(owner)
+ new_record = new_recommendation.new_record?
+
+ # return if it's the same recommendation as before
+ ( new_recommendation.touch and return true ) if ( not new_record and new_recommendation.recommendation == recommendation )
+
+ old_recommendation = new_recommendation.recommendation unless new_record
+
+ new_recommendation.recommendation = recommendation
+ new_recommendation.save
+
+ # adds the recommendation count to self if needed
+ self.good_recommendations += 1 if recommendation
+ self.bad_recommendations += 1 if not recommendation
+
+ # removes the old recomendation count if you are changing an old one
+ unless new_record
+ self.bad_recommendations -= 1 if recommendation && ( not old_recommendation )
+ self.good_recommendations -= 1 if !recommendation && old_recommendation
+ end
+
+ self.save
+ end
+
+ def recommendations
+ self.good_recommendations - self.bad_recommendations
+ end
+
+ def recommendations_count
+ self.good_recommendations + self.bad_recommendations
+ end
+
+ def good_recommendations_percent(format = '%.2f')
+ format % ((self.good_recommendations.to_f / (self.recommendations_count == 0 ? 1.to_f : self.recommendations_count.to_f)) * 100)
+ end
+
+ def bad_recommendations_percent(format = '%.2f')
+ format % ((self.bad_recommendations.to_f / (self.recommendations_count == 0 ? 1.to_f : self.recommendations_count.to_f)) * 100)
+ end
+
+ def recommended_by?(user)
+ Recommendation.of_item(self).owned_by(user).first ? true : false
+ end
+
+ def get_recommendation_of(user)
+ Recommendation.of_item(self).owned_by(user).first.recommendation
+ end
+
+ private
+
+ def _normalize_recommendation(recommendation)
+ (( recommendation.is_a?(String) || recommendation.is_a?(Fixnum) ) ? (recommendation.to_i == 1) : recommendation)
+ end
+
+ def _new_or_last_recommendation_for(owner)
+ Recommendation.of_item(self).owned_by(owner).first or Recommendation.new(:owner_id => owner.id, :recommendable_id => self.id, :recommendable_type => self.class.base_class.name)
+ end
+ end
+ end
+end
26 lib/generators/acts_as_recommended/recommendations_for/recommendations_for_generator.rb
@@ -0,0 +1,26 @@
+require 'rails/generators'
+require 'rails/generators/migration'
+
+module ActsAsRecommended
+ module Generators
+ class RecommendationsForGenerator < Rails::Generators::NamedBase
+ include Rails::Generators::Migration
+
+ def self.source_root
+ File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
+ end
+
+ def self.next_migration_number(dirname)
+ if ActiveRecord::Base.timestamped_migrations
+ Time.now.utc.strftime("%Y%m%d%H%M%S")
+ else
+ "%.3d" % (current_migration_number(dirname) + 1)
+ end
+ end
+
+ def manifest
+ migration_template "migrations/add_recommendations_to_table.rb", "db/migrate/add_recommendations_to_#{table_name}", {:assigns => {:name => name, :table_name => table_name}}
+ end
+ end
+ end
+end
BIN ...recommended/recommendations_for/templates/migrations/.add_recommendations_to_table.rb.swp
Binary file not shown.
11 ...s_as_recommended/recommendations_for/templates/migrations/add_recommendations_to_table.rb
@@ -0,0 +1,11 @@
+class AddRecommendationsTo<%= table_name.camelize %> < ActiveRecord::Migration
+ def self.up
+ add_column :<%= table_name %>, :good_recommendations, :integer, :default => 0
+ add_column :<%= table_name %>, :bad_recommendations, :integer, :default => 0
+ end
+
+ def self.down
+ remove_column :<%= table_name %>, :good_recommendations
+ remove_column :<%= table_name %>, :bad_recommendations
+ end
+end
8 lib/generators/acts_as_recommended/tables/USAGE
@@ -0,0 +1,8 @@
+Description:
+ Explain the generator
+
+Example:
+ ./script/generate acts_as_recommended Thing
+
+ This will create:
+ what/will/it/create
26 lib/generators/acts_as_recommended/tables/tables_generator.rb
@@ -0,0 +1,26 @@
+require 'rails/generators'
+require 'rails/generators/migration'
+
+module ActsAsRecommended
+ module Generators
+ class TablesGenerator < Rails::Generators::Base
+ include Rails::Generators::Migration
+
+ def self.source_root
+ File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
+ end
+
+ def self.next_migration_number(dirname)
+ if ActiveRecord::Base.timestamped_migrations
+ Time.now.utc.strftime("%Y%m%d%H%M%S")
+ else
+ "%.3d" % (current_migration_number(dirname) + 1)
+ end
+ end
+
+ def manifest
+ migration_template "migrations/create_recommendations.rb", "db/migrate/create_recommendations"
+ end
+ end
+ end
+end
BIN ...generators/acts_as_recommended/tables/templates/migrations/.create_recommendations.rb.swp
Binary file not shown.
19 lib/generators/acts_as_recommended/tables/templates/migrations/create_recommendations.rb
@@ -0,0 +1,19 @@
+class CreateRecommendations < ActiveRecord::Migration
+ def self.up
+ create_table :recommendations do |t|
+ t.references :recommendable, :polymorphic => true, :null => false
+ t.references :owner, :null => false
+ t.boolean :recommendation, :null => false
+
+ t.timestamps
+ end
+
+ add_index :recommendations, [:recommendable_type, :recommendable_id], :name => 'idx_recommendations'
+ add_index :recommendations, [:recommendable_type, :recommendable_id, :owner_id], :unique => true, :name => 'idx_recommendations_user'
+ add_index :recommendations, [:recommendable_type, :recommendable_id, :recommendation], :name => 'idx_recommendations_type'
+ end
+
+ def self.down
+ drop_table :recommendations
+ end
+end
BIN spec/.acts_as_recommended_spec.rb.swp
Binary file not shown.
BIN spec/.spec_helper.rb.swp
Binary file not shown.
70 spec/acts_as_recommended_spec.rb
@@ -0,0 +1,70 @@
+require 'spec_helper'
+
+describe ActsAsRecommended do
+
+ before(:all) do
+ Post.destroy_all
+ User.destroy_all
+
+ Post.acts_as_recommended
+ @post = Post.new(:title => "Test")
+ @post.save
+ @user = User.new(:name => "Bob")
+ @user.save
+ end
+
+ it "should be a module" do
+ ActsAsRecommended.should be_a(Module)
+ end
+
+ it "should add a recommendation" do
+ @post.recommend! true, @user
+
+ @post.recommendations.should == 1
+ @post.good_recommendations.should == 1
+ @post.bad_recommendations.should == 0
+ @post.bad_recommendations_percent.should == "0.00"
+ @post.good_recommendations_percent.should == "100.00"
+ end
+
+ it "should raise an error when adding a nil recommendation " do
+ lambda { @post.recommend! nil, @user }.should raise_error
+ end
+
+ it "should change a recommendation" do
+ user = User.new(:name => 'John')
+ user.save
+ @post.recommend! true, user
+ @post.recommend! true, @user
+
+ recommendations_tests(2, 0)
+
+ @post.recommend! false, user
+
+ recommendations_tests(1, 1)
+
+ @post.recommend! true, user
+
+ recommendations_tests(2, 0)
+ end
+
+ it "should get the recommendation of an user" do
+ lulu = User.new(:name => 'Lulu')
+ lulu.save
+
+ @post.recommend! true, lulu
+ recommendation = @post.get_recommendation_of lulu
+ recommendation.should be_true
+ end
+
+ private
+
+ def recommendations_tests(good, bad)
+ total = good + bad
+ @post.recommendations.should == (good - bad)
+ @post.good_recommendations.should == good
+ @post.bad_recommendations.should == bad
+ @post.bad_recommendations_percent.should == "%.2f" % (bad.to_f / (total == 0 ? 1.to_f : (total.to_f)) * 100)
+ @post.good_recommendations_percent.should == "%.2f" % (good.to_f / (total == 0 ? 1.to_f : (total.to_f)) * 100)
+ end
+end
7 spec/dummy/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'
+
+Dummy::Application.load_tasks
3 spec/dummy/app/controllers/application_controller.rb
@@ -0,0 +1,3 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+end
83 spec/dummy/app/controllers/posts_controller.rb
@@ -0,0 +1,83 @@
+class PostsController < ApplicationController
+ # GET /posts
+ # GET /posts.xml
+ def index
+ @posts = Post.all
+
+ respond_to do |format|
+ format.html # index.html.erb
+ format.xml { render :xml => @posts }
+ end
+ end
+
+ # GET /posts/1
+ # GET /posts/1.xml
+ def show
+ @post = Post.find(params[:id])
+
+ respond_to do |format|
+ format.html # show.html.erb
+ format.xml { render :xml => @post }
+ end
+ end
+
+ # GET /posts/new
+ # GET /posts/new.xml
+ def new
+ @post = Post.new
+
+ respond_to do |format|
+ format.html # new.html.erb
+ format.xml { render :xml => @post }
+ end
+ end
+
+ # GET /posts/1/edit
+ def edit
+ @post = Post.find(params[:id])
+ end
+
+ # POST /posts
+ # POST /posts.xml
+ def create
+ @post = Post.new(params[:post])
+
+ respond_to do |format|
+ if @post.save
+ format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
+ format.xml { render :xml => @post, :status => :created, :location => @post }
+ else
+ format.html { render :action => "new" }
+ format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
+ end
+ end
+ end
+
+ # PUT /posts/1
+ # PUT /posts/1.xml
+ def update
+ @post = Post.find(params[:id])
+
+ respond_to do |format|
+ if @post.update_attributes(params[:post])
+ format.html { redirect_to(@post, :notice => 'Post was successfully updated.') }
+ format.xml { head :ok }
+ else
+ format.html { render :action => "edit" }
+ format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
+ end
+ end
+ end
+
+ # DELETE /posts/1
+ # DELETE /posts/1.xml
+ def destroy
+ @post = Post.find(params[:id])
+ @post.destroy
+
+ respond_to do |format|
+ format.html { redirect_to(posts_url) }
+ format.xml { head :ok }
+ end
+ end
+end
2 spec/dummy/app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
2 spec/dummy/app/helpers/posts_helper.rb
@@ -0,0 +1,2 @@
+module PostsHelper
+end
2 spec/dummy/app/models/post.rb
@@ -0,0 +1,2 @@
+class Post < ActiveRecord::Base
+end
2 spec/dummy/app/models/user.rb
@@ -0,0 +1,2 @@
+class User < ActiveRecord::Base
+end
14 spec/dummy/app/views/layouts/application.html.erb
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Dummy</title>
+ <%= stylesheet_link_tag :all %>
+ <%= javascript_include_tag :defaults %>
+ <%= csrf_meta_tag %>
+</head>
+<body>
+
+<%= yield %>
+
+</body>
+</html>
21 spec/dummy/app/views/posts/_form.html.erb
@@ -0,0 +1,21 @@
+<%= form_for(@post) do |f| %>
+ <% if @post.errors.any? %>
+ <div id="error_explanation">
+ <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
+
+ <ul>
+ <% @post.errors.full_messages.each do |msg| %>
+ <li><%= msg %></li>
+ <% end %>
+ </ul>
+ </div>
+ <% end %>
+
+ <div class="field">
+ <%= f.label :title %><br />
+ <%= f.text_field :title %>
+ </div>
+ <div class="actions">
+ <%= f.submit %>
+ </div>
+<% end %>
6 spec/dummy/app/views/posts/edit.html.erb
@@ -0,0 +1,6 @@
+<h1>Editing post</h1>
+
+<%= render 'form' %>
+
+<%= link_to 'Show', @post %> |
+<%= link_to 'Back', posts_path %>
23 spec/dummy/app/views/posts/index.html.erb
@@ -0,0 +1,23 @@
+<h1>Listing posts</h1>
+
+<table>
+ <tr>
+ <th>Title</th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+
+<% @posts.each do |post| %>
+ <tr>
+ <td><%= post.title %></td>
+ <td><%= link_to 'Show', post %></td>
+ <td><%= link_to 'Edit', edit_post_path(post) %></td>
+ <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>
+ </tr>
+<% end %>
+</table>
+
+<br />
+
+<%= link_to 'New Post', new_post_path %>
5 spec/dummy/app/views/posts/new.html.erb
@@ -0,0 +1,5 @@
+<h1>New post</h1>
+
+<%= render 'form' %>
+
+<%= link_to 'Back', posts_path %>
10 spec/dummy/app/views/posts/show.html.erb
@@ -0,0 +1,10 @@
+<p id="notice"><%= notice %></p>
+
+<p>
+ <b>Title:</b>
+ <%= @post.title %>
+</p>
+
+
+<%= link_to 'Edit', edit_post_path(@post) %> |
+<%= link_to 'Back', posts_path %>
4 spec/dummy/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 Dummy::Application
45 spec/dummy/config/application.rb
@@ -0,0 +1,45 @@
+require File.expand_path('../boot', __FILE__)
+
+require "active_model/railtie"
+require "active_record/railtie"
+require "action_controller/railtie"
+require "action_view/railtie"
+require "action_mailer/railtie"
+
+Bundler.require
+require "acts_as_recommended"
+
+module Dummy
+ 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
10 spec/dummy/config/boot.rb
@@ -0,0 +1,10 @@
+require 'rubygems'
+gemfile = File.expand_path('../../../../Gemfile', __FILE__)
+
+if File.exist?(gemfile)
+ ENV['BUNDLE_GEMFILE'] = gemfile
+ require 'bundler'
+ Bundler.setup
+end
+
+$:.unshift File.expand_path('../../../../lib', __FILE__)
22 spec/dummy/config/database.yml
@@ -0,0 +1,22 @@
+# SQLite version 3.x
+# gem install sqlite3
+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
5 spec/dummy/config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application
+Dummy::Application.initialize!
26 spec/dummy/config/environments/development.rb
@@ -0,0 +1,26 @@
+Dummy::Application.configure do
+ # Settings specified here will take precedence over those in config/application.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
+end
+
49 spec/dummy/config/environments/production.rb
@@ -0,0 +1,49 @@
+Dummy::Application.configure do
+ # Settings specified here will take precedence over those in config/application.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
35 spec/dummy/config/environments/test.rb
@@ -0,0 +1,35 @@
+Dummy::Application.configure do
+ # Settings specified here will take precedence over those in config/application.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
7 spec/dummy/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!
10 spec/dummy/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
5 spec/dummy/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
7 spec/dummy/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.
+Dummy::Application.config.secret_token = '88432fafd634b15f723df287d08e9dd6dcb331ca8f327bee8763d0875d593633ff056dcd092bd259213b6fea829c32dbebd9efe07d177809265d1904b170abeb'
8 spec/dummy/config/initializers/session_store.rb
@@ -0,0 +1,8 @@
+# Be sure to restart your server when you modify this file.
+
+Dummy::Application.config.session_store :cookie_store, :key => '_dummy_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 "rails generate session_migration")
+# Dummy::Application.config.session_store :active_record_store
5 spec/dummy/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"
60 spec/dummy/config/routes.rb
@@ -0,0 +1,60 @@
+Dummy::Application.routes.draw do
+ resources :posts
+
+ # The priority is based upon order of creation:
+ # first created -> highest priority.
+
+ # Sample of regular route:
+ # match 'products/:id' => 'catalog#view'
+ # Keep in mind you can assign values other than :controller and :action
+
+ # Sample of named route:
+ # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
+ # This route can be invoked with purchase_url(:id => product.id)
+
+ # Sample resource route (maps HTTP verbs to controller actions automatically):
+ # resources :products
+
+ # Sample resource route with options:
+ # resources :products do
+ # member do
+ # get 'short'
+ # post 'toggle'
+ # end
+ #
+ # collection do
+ # get 'sold'
+ # end
+ # end
+
+ # Sample resource route with sub-resources:
+ # resources :products do
+ # resources :comments, :sales
+ # resource :seller
+ # end
+
+ # Sample resource route with more complex sub-resources
+ # resources :products do
+ # resources :comments
+ # resources :sales do
+ # get 'recent', :on => :collection
+ # end
+ # end
+
+ # Sample resource route within a namespace:
+ # namespace :admin do
+ # # Directs /admin/products/* to Admin::ProductsController
+ # # (app/controllers/admin/products_controller.rb)
+ # resources :products
+ # end
+
+ # You can have the root of your site routed with "root"
+ # just remember to delete public/index.html.
+ # root :to => "welcome#index"
+
+ # See how all your routes lay out with "rake routes"
+
+ # This is a legacy wild controller route that's not recommended for RESTful applications.
+ # Note: This route will make all actions in every controller accessible via GET requests.
+ # match ':controller(/:action(/:id(.:format)))'
+end
13 spec/dummy/db/migrate/20110617123838_create_posts.rb
@@ -0,0 +1,13 @@
+class CreatePosts < ActiveRecord::Migration
+ def self.up
+ create_table :posts do |t|
+ t.string :title
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :posts
+ end
+end
13 spec/dummy/db/migrate/20110617123848_create_users.rb
@@ -0,0 +1,13 @@
+class CreateUsers < ActiveRecord::Migration
+ def self.up
+ create_table :users do |t|
+ t.string :name
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :users
+ end
+end
19 spec/dummy/db/migrate/20110617125425_create_recommendations.rb
@@ -0,0 +1,19 @@
+class CreateRecommendations < ActiveRecord::Migration
+ def self.up
+ create_table :recommendations do |t|
+ t.references :recommendable, :polymorphic => true, :null => false
+ t.references :owner, :null => false
+ t.boolean :recommendation, :null => false
+
+ t.timestamps
+ end
+
+ add_index :recommendations, [:recommendable_type, :recommendable_id], :name => 'idx_recommendations'
+ add_index :recommendations, [:recommendable_type, :recommendable_id, :owner_id], :unique => true, :name => 'idx_recommendations_user'
+ add_index :recommendations, [:recommendable_type, :recommendable_id, :recommendation], :name => 'idx_recommendations_type'
+ end
+
+ def self.down
+ drop_table :recommendations
+ end
+end
11 spec/dummy/db/migrate/20110617125441_add_recommendations_to_posts.rb
@@ -0,0 +1,11 @@
+class AddRecommendationsToPosts < ActiveRecord::Migration
+ def self.up
+ add_column :posts, :good_recommendations, :integer, :default => 0
+ add_column :posts, :bad_recommendations, :integer, :default => 0
+ end
+
+ def self.down
+ remove_column :posts, :good_recommendations
+ remove_column :posts, :bad_recommendations
+ end
+end
26 spec/dummy/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>
26 spec/dummy/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>
26 spec/dummy/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>
0 spec/dummy/public/favicon.ico
No changes.
2 spec/dummy/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
965 spec/dummy/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.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