From: Ira W. Snyder Date: Thu, 22 Nov 2007 18:57:30 +0000 (-0800) Subject: Add the has_many_polymorphs plugin X-Git-Tag: turned-in~63 X-Git-Url: https://www.irasnyder.com/gitweb/?p=cs356-p2-videostore.git;a=commitdiff_plain;h=97369db0c55dbf9d52059116497995481d9d163d Add the has_many_polymorphs plugin See http://m.onkey.org/2007/8/14/excuse-me-wtf-is-polymorphs for a tutorial / walkthrough. Signed-off-by: Ira W. Snyder --- diff --git a/vendor/plugins/has_many_polymorphs/CHANGELOG b/vendor/plugins/has_many_polymorphs/CHANGELOG new file mode 100644 index 0000000..becb4f2 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/CHANGELOG @@ -0,0 +1,79 @@ + +v2.10. Add :parent_conditions option; bugfix for nullified conditions; bugfix for self-referential tagging generator; allow setting of has_many_polymorphs_options hash in Configuration's after_initialize if you need to adjust the autoload behavior; clear error message on missing or improperly namespaced models; fix .build on double-sided relationships; add :namespace key for easier set up of Camping apps or other unusual class structures. + +v2.9. Gem version renumbering; my apologies if this messes anyone up. + +v2.8. RDoc documentation; repository relocation; Rakefile cleanup; remove deprecated plugin-specific class caching. + +v2.7.5. Various bugfixes; Postgres problems may remain on edge. + +v2.7.3. Use new :source and :source_type options in 1.2.3 (David Lemstra); fix pluralization bug; add some tests; experimental tagging generator. + +v2.7.2. Deprecate has_many_polymorphs_cache_classes= option because it doesn't really work. Use config.cache_classes= instead to cache all reloadable items. + +v2.7.1. Dispatcher.to_prepare didn't fire in the console; now using a config.after_initialize wrapper instead. + +v2.7. Dependency injection framework elimates having to care about load order. + +v2.6. Make the logger act sane for the gem version. + +v2.5.2. Allow :skip_duplicates on double relationships. + +v2.5.1. Renamed :ignore_duplicates to :skip_duplicates to better express its non-passive behavior; made sure not to load target set on push unless necessary. + +v2.5. Activerecord compatibility branch becomes trunk: extra options now supported for double polymorphism; conditions nulled-out and propogated to child relationships; more tests; new :ignore_duplicates option on macro can be set to false if you want << to push duplicate associations. + +v2.4.1. Code split into multiple files; tests added for pluralization check; Rails 1.1.6 no longer supported. + +v2.4. Unlimited mixed class association extensions for both single and double targets and joins. + +v2.3. Gem version + +v2.2. API change; prefix on methods is now singular when using :rename_individual_collections. + +v2.1. Add configuration option to cache polymorphic classes in development mode. + +v2.0. Collection methods (push, delete, clear) now on individual collections. + +v1.9.2. Disjoint collection sides bugfix, don't raise on new records. + +v1.9.1. Double classify bugfix. + +v1.9. Large changes to properly support double polymorphism. + +v1.8.2. Bugfix to make sure the type gets checked on doubly polymorphic parents. + +v1.8.1. Bugfix for sqlite3 child attribute retrieval. + +v1.8. Bugfix for instantiating attributes of namespaced models. + +v1.7.1. Bugfix for double polymorphic relationships. + +v1.7. Double polymorphic relationships (includes new API method). + +v1.6. Namespaced model support. + +v1.5. Bugfix for Postgres and Mysql under 1.1.6; refactored tests (hildofur); properly handles legacy table names set with set_table_name(). + +v1.4. STI support added (use the child class names, not the base class). + +v1.3. Bug regarding table names with underscores in SQL query fixed. + +v1.2. License change, again. + +v1.1. File_column bug fixed. + +v1.0. Tests written; after_find and after_initialize now correctly called. + +v0.5. SQL performance enhancements added. + +v0.4. Rewrote singletons as full-fledged proxy class so that marshalling works (e.g. in the session). + +v0.3. Caching added. + +v0.2. Fixed dependency reloading problem in development mode. + +v0.1. License change. + +v0. Added :dependent support on the join table; no changelog before this version. + diff --git a/vendor/plugins/has_many_polymorphs/LICENSE b/vendor/plugins/has_many_polymorphs/LICENSE new file mode 100644 index 0000000..90eec26 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/LICENSE @@ -0,0 +1,184 @@ +Academic Free License (AFL) v. 3.0 + +This Academic Free License (the "License") applies to any original work +of authorship (the "Original Work") whose owner (the "Licensor") has +placed the following licensing notice adjacent to the copyright notice +for the Original Work: + +Licensed under the Academic Free License version 3.0 + +1) Grant of Copyright License. Licensor grants You a worldwide, +royalty-free, non-exclusive, sublicensable license, for the duration of +the copyright, to do the following: + +a) to reproduce the Original Work in copies, either alone or as part of +a collective work; + +b) to translate, adapt, alter, transform, modify, or arrange the +Original Work, thereby creating derivative works ("Derivative Works") +based upon the Original Work; + +c) to distribute or communicate copies of the Original Work and +Derivative Works to the public, under any license of your choice that +does not contradict the terms and conditions, including Licensor's +reserved rights and remedies, in this Academic Free License; + +d) to perform the Original Work publicly; and + +e) to display the Original Work publicly. + +2) Grant of Patent License. Licensor grants You a worldwide, +royalty-free, non-exclusive, sublicensable license, under patent claims +owned or controlled by the Licensor that are embodied in the Original +Work as furnished by the Licensor, for the duration of the patents, to +make, use, sell, offer for sale, have made, and import the Original Work +and Derivative Works. + +3) Grant of Source Code License. The term "Source Code" means the +preferred form of the Original Work for making modifications to it and +all available documentation describing how to modify the Original Work. +Licensor agrees to provide a machine-readable copy of the Source Code of +the Original Work along with each copy of the Original Work that +Licensor distributes. Licensor reserves the right to satisfy this +obligation by placing a machine-readable copy of the Source Code in an +information repository reasonably calculated to permit inexpensive and +convenient access by You for as long as Licensor continues to distribute +the Original Work. + +4) Exclusions From License Grant. Neither the names of Licensor, nor the +names of any contributors to the Original Work, nor any of their +trademarks or service marks, may be used to endorse or promote products +derived from this Original Work without express prior permission of the +Licensor. Except as expressly stated herein, nothing in this License +grants any license to Licensor's trademarks, copyrights, patents, trade +secrets or any other intellectual property. No patent license is granted +to make, use, sell, offer for sale, have made, or import embodiments of +any patent claims other than the licensed claims defined in Section 2. +No license is granted to the trademarks of Licensor even if such marks +are included in the Original Work. Nothing in this License shall be +interpreted to prohibit Licensor from licensing under terms different +from this License any Original Work that Licensor otherwise would have a +right to license. + +5) External Deployment. The term "External Deployment" means the use, +distribution, or communication of the Original Work or Derivative Works +in any way such that the Original Work or Derivative Works may be used +by anyone other than You, whether those works are distributed or +communicated to those persons or made available as an application +intended for use over a network. As an express condition for the grants +of license hereunder, You must treat any External Deployment by You of +the Original Work or a Derivative Work as a distribution under section +1(c). + +6) Attribution Rights. You must retain, in the Source Code of any +Derivative Works that You create, all copyright, patent, or trademark +notices from the Source Code of the Original Work, as well as any +notices of licensing and any descriptive text identified therein as an +"Attribution Notice." You must cause the Source Code for any Derivative +Works that You create to carry a prominent Attribution Notice reasonably +calculated to inform recipients that You have modified the Original +Work. + +7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants +that the copyright in and to the Original Work and the patent rights +granted herein by Licensor are owned by the Licensor or are sublicensed +to You under the terms of this License with the permission of the +contributor(s) of those copyrights and patent rights. Except as +expressly stated in the immediately preceding sentence, the Original +Work is provided under this License on an "AS IS" BASIS and WITHOUT +WARRANTY, either express or implied, including, without limitation, the +warranties of non-infringement, merchantability or fitness for a +particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL +WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential +part of this License. No license to the Original Work is granted by this +License except under this disclaimer. + +8) Limitation of Liability. Under no circumstances and under no legal +theory, whether in tort (including negligence), contract, or otherwise, +shall the Licensor be liable to anyone for any indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or the use of the Original Work including, +without limitation, damages for loss of goodwill, work stoppage, +computer failure or malfunction, or any and all other commercial damages +or losses. This limitation of liability shall not apply to the extent +applicable law prohibits such limitation. + +9) Acceptance and Termination. If, at any time, You expressly assented +to this License, that assent indicates your clear and irrevocable +acceptance of this License and all of its terms and conditions. If You +distribute or communicate copies of the Original Work or a Derivative +Work, You must make a reasonable effort under the circumstances to +obtain the express assent of recipients to the terms of this License. +This License conditions your rights to undertake the activities listed +in Section 1, including your right to create Derivative Works based upon +the Original Work, and doing so without honoring these terms and +conditions is prohibited by copyright law and international treaty. +Nothing in this License is intended to affect copyright exceptions and +limitations (including "fair use" or "fair dealing"). This License shall +terminate immediately and You may no longer exercise any of the rights +granted to You by this License upon your failure to honor the conditions +in Section 1(c). + +10) Termination for Patent Action. This License shall terminate +automatically and You may no longer exercise any of the rights granted +to You by this License as of the date You commence an action, including +a cross-claim or counterclaim, against Licensor or any licensee alleging +that the Original Work infringes a patent. This termination provision +shall not apply for an action alleging patent infringement by +combinations of the Original Work with other software or hardware. + +11) Jurisdiction, Venue and Governing Law. Any action or suit relating +to this License may be brought only in the courts of a jurisdiction +wherein the Licensor resides or in which Licensor conducts its primary +business, and under the laws of that jurisdiction excluding its +conflict-of-law provisions. The application of the United Nations +Convention on Contracts for the International Sale of Goods is expressly +excluded. Any use of the Original Work outside the scope of this License +or after its termination shall be subject to the requirements and +penalties of copyright or patent law in the appropriate jurisdiction. +This section shall survive the termination of this License. + +12) Attorneys' Fees. In any action to enforce the terms of this License +or seeking damages relating thereto, the prevailing party shall be +entitled to recover its costs and expenses, including, without +limitation, reasonable attorneys' fees and costs incurred in connection +with such action, including any appeal of such action. This section +shall survive the termination of this License. + +13) Miscellaneous. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. + +14) Definition of "You" in This License. "You" throughout this License, +whether in upper or lower case, means an individual or a legal entity +exercising rights under, and complying with all of the terms of, this +License. For legal entities, "You" includes any entity that controls, is +controlled by, or is under common control with you. For purposes of this +definition, "control" means (i) the power, direct or indirect, to cause +the direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +15) Right to Use. You may use the Original Work in all ways not +otherwise restricted or conditioned by this License or by law, and +Licensor promises not to interfere with or be responsible for such uses +by You. + +16) Modification of This License. This License is Copyright (c) 2005 +Lawrence Rosen. Permission is granted to copy, distribute, or +communicate this License without modification. Nothing in this License +permits You to modify this License as applied to the Original Work or to +Derivative Works. However, You may modify the text of this License and +copy, distribute or communicate your modified version (the "Modified +License") and apply it to other original works of authorship subject to +the following conditions: (i) You may not indicate in any way that your +Modified License is the "Academic Free License" or "AFL" and you may not +use those names in the name of your Modified License; (ii) You must +replace the notice specified in the first paragraph above with the +notice "Licensed under " or with a notice +of your own that is not confusingly similar to the notice in this +License; and (iii) You may not claim that your original works are open +source software unless your Modified License has been approved by Open +Source Initiative (OSI) and You comply with its license review and +certification process. + diff --git a/vendor/plugins/has_many_polymorphs/Manifest b/vendor/plugins/has_many_polymorphs/Manifest new file mode 100644 index 0000000..f05a2d0 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/Manifest @@ -0,0 +1,57 @@ +TODO +test/unit/polymorph_test.rb +test/test_helper.rb +test/schema.rb +test/modules/other_extension_module.rb +test/modules/extension_module.rb +test/models/wild_boar.rb +test/models/tabby.rb +test/models/petfood.rb +test/models/person.rb +test/models/parentship.rb +test/models/kitten.rb +test/models/frog.rb +test/models/eaters_foodstuff.rb +test/models/dog.rb +test/models/cat.rb +test/models/canine.rb +test/models/beautiful_fight_relationship.rb +test/models/aquatic/whale.rb +test/models/aquatic/pupils_whale.rb +test/models/aquatic/fish.rb +test/fixtures/wild_boars.yml +test/fixtures/petfoods.yml +test/fixtures/people.yml +test/fixtures/keep_your_enemies_close.yml +test/fixtures/frogs.yml +test/fixtures/eaters_foodstuffs.yml +test/fixtures/cats.yml +test/fixtures/bow_wows.yml +test/fixtures/aquatic/whales.yml +test/fixtures/aquatic/little_whale_pupils.yml +test/fixtures/aquatic/fish.yml +README +Manifest +LICENSE +lib/has_many_polymorphs.rb +lib/has_many_polymorphs/support_methods.rb +lib/has_many_polymorphs/reflection.rb +lib/has_many_polymorphs/rake_task_redefine_task.rb +lib/has_many_polymorphs/dependencies.rb +lib/has_many_polymorphs/debugging_tools.rb +lib/has_many_polymorphs/configuration.rb +lib/has_many_polymorphs/class_methods.rb +lib/has_many_polymorphs/base.rb +lib/has_many_polymorphs/autoload.rb +lib/has_many_polymorphs/association.rb +init.rb +generators/tagging/templates/tags.yml +generators/tagging/templates/taggings.yml +generators/tagging/templates/tagging_test.rb +generators/tagging/templates/tagging_extensions.rb +generators/tagging/templates/tagging.rb +generators/tagging/templates/tag_test.rb +generators/tagging/templates/tag.rb +generators/tagging/templates/migration.rb +generators/tagging/tagging_generator.rb +CHANGELOG diff --git a/vendor/plugins/has_many_polymorphs/README b/vendor/plugins/has_many_polymorphs/README new file mode 100644 index 0000000..7413582 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/README @@ -0,0 +1,174 @@ + +Has_many_polymorphs + +An ActiveRecord plugin for self-referential and double-sided polymorphic associations. + +== License + +Copyright 2007 Cloudburst, LLC. Licensed under the AFL 3. See the included LICENSE file. + +The public certificate for this gem is at http://rubyforge.org/frs/download.php/25331/evan_weaver-original-public_cert.pem. + +== Description + +This plugin lets you define self-referential and double-sided polymorphic associations in your models. It is an extension of has_many :through. + +“Polymorphic” means an association can freely point to any of several unrelated model classes, instead of being tied to one particular class. + +== Features + +* self-references +* double-sided polymorphism +* efficient database usage +* STI support +* namespace support +* automatic individual and reverse associations + +The plugin also includes a generator for a tagging system, a common use case (see below). + +== Requirements + +* Rails 1.2.3 or greater + += Usage + +== Installation + +To install the Rails plugin, run: + script/plugin install svn://rubyforge.org/var/svn/fauna/has_many_polymorphs/trunk + +There's also a gem version. To install it instead, run: + sudo gem install has_many_polymorphs + +If you are using the gem, make sure to add require 'has_many_polymorphs' to environment.rb, before Rails::Initializer block. + +== Configuration + +Setup the parent model as so: + + class Kennel < ActiveRecord::Base + has_many_polymorphs :guests, :from => [:dogs, :cats, :birds] + end + +The join model: + + class GuestsKennel < ActiveRecord::Base + belongs_to :kennel + belongs_to :guest, :polymorphic => true + end + +One of the child models: + + class Dog < ActiveRecord::Base + # nothing + end + +See ActiveRecord::Associations::PolymorphicClassMethods for more configuration options. + +== Helper methods example + + >> k = Kennel.find(1) + # + >> k.guests.map(&:class) + [Dog, Cat, Cat, Bird] + + >> k.guests.push(Cat.create); k.cats.size + 3 + >> k.guests << Cat.create; k.cats.size + 4 + >> k.guests.size + 6 + + >> d = k.dogs.first + # + >> d.kennels + [#] + + >> k.guests.delete(d); k.dogs.size + 0 + >> k.guests.size + 5 + +Note that the parent method is always plural, even if there is only one parent (Dog#kennels, not Dog#kennel). + +See ActiveRecord::Associations::PolymorphicAssociation for more helper method details. + += Extras + +== Double-sided polymorphism + +Double-sided relationships are defined on the join model: + + class Devouring < ActiveRecord::Base + belongs_to :guest, :polymorphic => true + belongs_to :eaten, :polymorphic => true + + acts_as_double_polymorphic_join( + :guests =>[:dogs, :cats], + :eatens => [:cats, :birds] + ) + end + +Now, dogs and cats can eat birds and cats. Birds can't eat anything (they aren't guests) and dogs can't be eaten by anything (since they aren't eatens). The keys stand for what the models are, not what they do. + +In this case, each guest/eaten relationship is called a Devouring. + +See ActiveRecord::Associations::PolymorphicClassMethods for more. + +== Tagging generator + +Has_many_polymorphs includes a tagging system generator. Run: + script/generate tagging Dog Cat [...MoreModels...] + +This adds a migration and new Tag and Tagging models in app/models. It configures Tag with an appropriate has_many_polymorphs call against the models you list at the command line. It also adds the file lib/tagging_extensions.rb and requires it in environment.rb. + +Tests will also be generated. + +Once you've run the generator, you can tag records as follows: + + >> d = Dog.create(:name => "Rover") + # + >> d.tag_list + "" + >> d.tag_with "fierce loud" + # + >> d.tag_list + "fierce loud" + >> c = Cat.create(:name => "Chloe") + # + >> c.tag_with "fierce cute" + # + >> c.tag_list + "cute fierce" + >> Tag.find_by_name("fierce").taggables + [#, #] + +The generator accepts the optional flag --skip-migration to skip generating a migration (for example, if you are converting from acts_as_taggable). It also accepts the flag --self-referential if you want to be able to tag tags. + +See ActiveRecord::Base::TaggingExtensions, Tag, and Tagging for more. + +== Troubleshooting + +Some debugging tools are available in lib/has_many_polymorphs/debugging_tools.rb. + +If you are having trouble, think very carefully about how your model classes, key columns, and table names relate. You may have to explicitly specify options on your join model such as :class_name, :foreign_key, or :as. The included tests are a good place to look for examples. + +Note that because of the way Rails reloads model classes, the plugin can sometimes bog down your development server. Set config.cache_classes = true in config/environments/development.rb to avoid this. + +== Reporting problems + +* http://rubyforge.org/forum/forum.php?forum_id=16450 + +Patches and contributions are very welcome. Please note that contributors are required to assign copyright for their additions to Cloudburst, LLC. + +== Further resources + +* http://blog.evanweaver.com/articles/2007/08/15/polymorphs-tutorial +* http://blog.evanweaver.com/articles/2007/02/22/polymorphs-25-total-insanity-branch +* http://blog.evanweaver.com/articles/2007/02/09/how-to-find-the-most-popular-tags +* http://blog.evanweaver.com/articles/2007/01/13/growing-up-your-acts_as_taggable +* http://blog.evanweaver.com/articles/2006/12/02/polymorphs-19 +* http://blog.evanweaver.com/articles/2006/11/05/directed-double-polymorphic-associations +* http://blog.evanweaver.com/articles/2006/11/04/namespaced-model-support-in-has_many_polymorphs +* http://blog.evanweaver.com/articles/2006/09/26/sti-support-in-has_many_polymorphs +* http://blog.evanweaver.com/articles/2006/09/11/make-polymorphic-children-belong-to-only-one-parent diff --git a/vendor/plugins/has_many_polymorphs/Rakefile b/vendor/plugins/has_many_polymorphs/Rakefile new file mode 100644 index 0000000..f809313 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/Rakefile @@ -0,0 +1,21 @@ + +require 'rubygems' +gem 'echoe', '>=2.2' +require 'echoe' +require 'lib/has_many_polymorphs/rake_task_redefine_task' + +Echoe.new("has_many_polymorphs") do |p| + p.project = "fauna" + p.summary = "An ActiveRecord plugin for self-referential and double-sided polymorphic associations." + p.url = "http://blog.evanweaver.com/files/doc/fauna/has_many_polymorphs/" + p.docs_host = "blog.evanweaver.com:~/www/bax/public/files/doc/" + p.dependencies = ["activerecord"] + p.rdoc_pattern = /polymorphs\/association|polymorphs\/class_methods|polymorphs\/reflection|polymorphs\/autoload|polymorphs\/configuration|README|CHANGELOG|TODO|LICENSE|templates\/migration\.rb|templates\/tag\.rb|templates\/tagging\.rb|templates\/tagging_extensions\.rb/ + p.require_signed = true +end + +desc 'Run the test suite.' +Rake::Task.redefine_task("test") do + puts "Warning! Tests must be run with the plugin installed in a functioning Rails\nenvironment." + system "ruby -Ibin:lib:test test/unit/polymorph_test.rb #{ENV['METHOD'] ? "--name=#{ENV['METHOD']}" : ""}" +end diff --git a/vendor/plugins/has_many_polymorphs/TODO b/vendor/plugins/has_many_polymorphs/TODO new file mode 100644 index 0000000..4deb736 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/TODO @@ -0,0 +1,5 @@ + +* Does :namespace key definitely work with doubles? +* Migration examples in docs +* Controller for tagging generator +* Tag cloud method diff --git a/vendor/plugins/has_many_polymorphs/examples/hmph.rb b/vendor/plugins/has_many_polymorphs/examples/hmph.rb new file mode 100644 index 0000000..6701750 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/examples/hmph.rb @@ -0,0 +1,69 @@ +require 'camping' +require 'has_many_polymorphs' + +Camping.goes :Hmph + +module Hmph::Models + class GuestsKennel < Base + belongs_to :kennel + belongs_to :guest, :polymorphic => true + end + + class Dog < Base + end + + class Cat < Base + end + + class Bird < Base + end + + class Kennel < Base + has_many_polymorphs :guests, + :from => [:dogs, :cats, :birds], + :through => :guests_kennels, + :namespace => :"hmph/models/" + end + + class InitialSchema < V 1.0 + def self.up + create_table :hmph_kennels do |t| + t.column :created_at, :datetime + t.column :modified_at, :datetime + t.column :name, :string, :default => 'Anonymous Kennel' + end + + create_table :hmph_guests_kennels do |t| + t.column :guest_id, :integer + t.column :guest_type, :string + t.column :kennel_id, :integer + end + + create_table :hmph_dogs do |t| + t.column :name, :string, :default => 'Fido' + end + + create_table :hmph_cats do |t| + t.column :name, :string, :default => 'Morris' + end + + create_table :hmph_birds do |t| + t.column :name, :string, :default => 'Polly' + end + end + + def self.down + drop_table :hmph_kennels + drop_table :hmph_guests_kennels + drop_table :hmph_dogs + drop_table :hmph_cats + drop_table :hmph_birds + end + end +end + +module Hmph::Controllers +end + +module Hmph::Views +end diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/commenting_generator.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/commenting_generator.rb new file mode 100644 index 0000000..f4842af --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/commenting/commenting_generator.rb @@ -0,0 +1,94 @@ + +class CommentingGenerator < Rails::Generator::NamedBase + default_options :skip_migration => false + default_options :self_referential => false + attr_reader :parent_association_name + attr_reader :commentable_models + + def initialize(runtime_args, runtime_options = {}) + @parent_association_name = (runtime_args.include?("--self-referential") ? "commenter" : "comment") + @commentable_models = runtime_args.reject{|opt| opt =~ /^--/}.map do |commentable| + ":" + commentable.underscore.pluralize + end + @commentable_models += [":comments"] if runtime_args.include?("--self-referential") + @commentable_models.uniq! + + verify @commentable_models + hacks + runtime_args.unshift("placeholder") + super + end + + def verify models + puts "** Warning: only one commentable model specified; tests may not run properly." if models.size < 2 + models.each do |model| + model = model[1..-1].classify + next if model == "Comment" # don't load ourselves when --self-referential is used + self.class.const_get(model) rescue puts "** Error: model #{model[1..-1].classify} could not be loaded." or exit + end + end + + def hacks + # add the extension require in environment.rb + phrase = "require 'commenting_extensions'" + filename = "#{RAILS_ROOT}/config/environment.rb" + unless (open(filename) do |file| + file.grep(/#{Regexp.escape phrase}/).any? + end) + open(filename, 'a+') do |file| + file.puts "\n" + phrase + "\n" + end + end + end + + def manifest + record do |m| + m.class_collisions class_path, class_name, "#{class_name}Test" + + m.directory File.join('app/models', class_path) + m.directory File.join('test/unit', class_path) + m.directory File.join('test/fixtures', class_path) + m.directory File.join('test/fixtures', class_path) + m.directory File.join('lib') + + m.template 'comment.rb', File.join('app/models', class_path, "comment.rb") + m.template 'comment_test.rb', File.join('test/unit', class_path, "comment_test.rb") + m.template 'comments.yml', File.join('test/fixtures', class_path, "comments.yml") + + m.template 'commenting.rb', File.join('app/models', class_path, "commenting.rb") + m.template 'commenting_test.rb', File.join('test/unit', class_path, "commenting_test.rb") + m.template 'commentings.yml', File.join('test/fixtures', class_path, "commentings.yml") + + m.template 'commenting_extensions.rb', File.join('lib', 'commenting_extensions.rb') + + unless options[:skip_migration] + m.migration_template 'migration.rb', 'db/migrate', + :migration_file_name => "create_comments_and_commentings" + end + + end + end + + protected + def banner + "Usage: #{$0} generate commenting [CommentableModelA CommentableModelB ...]" + end + + def add_options!(opt) + opt.separator '' + opt.separator 'Options:' + opt.on("--skip-migration", + "Don't generate a migration file for this model") { |v| options[:skip_migration] = v } + opt.on("--self-referential", + "Allow comments to comment themselves.") { |v| options[:self_referential] = v } + end + + # Useful for generating tests/fixtures + def model_one + commentable_models[0][1..-1].classify + end + + def model_two + commentable_models[1][1..-1].classify rescue model_one + end +end diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment.rb new file mode 100644 index 0000000..4c1e822 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment.rb @@ -0,0 +1,33 @@ + +# The Comment model. This model is automatically generated and added to your app if you run the commenting generator. + +class Comment < ActiveRecord::Base + + # If database speed becomes an issue, you could remove these validations and rescue the ActiveRecord database constraint errors instead. + validates_presence_of :name, :email, :body + validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i + + after_validation :prepend_url + + # Set up the polymorphic relationship. + has_many_polymorphs :commentables, + :from => [<%= commentable_models.join(", ") %>], + :through => :commentings, + :dependent => :destroy, +<% if options[:self_referential] -%> :as => :<%= parent_association_name -%>, +<% end -%> + :parent_extend => proc { + } + + # Tag::Error class. Raised by ActiveRecord::Base::TaggingExtensions if something goes wrong. + class Error < StandardError + end + + protected + def prepend_url + return if self[:url].blank? + if self[:url] !~ /^http(s):\/\//i + self.url = 'http://' + self[:url] + end + end +end diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment_test.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment_test.rb new file mode 100644 index 0000000..b04c9ce --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comment_test.rb @@ -0,0 +1,12 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class CommentTest < Test::Unit::TestCase + fixtures :comments, :commentings, <%= commentable_models[0..1].join(", ") -%> + + def test_to_s + assert_equal "no1@nowhere.com", <%= model_two -%>.find(2).comments.first.email + assert_equal "http://letrails.cn", <%= model_two -%>.find(2).comments.last.url + assert_equal "http://fr.ivolo.us", <%= model_two -%>.find(2).comments.first.url + end + +end diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting.rb new file mode 100644 index 0000000..f429dbc --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting.rb @@ -0,0 +1,13 @@ + +# The Commenting join model. This model is automatically generated and added to your app if you run the commenting generator. + +class Commenting < ActiveRecord::Base + + belongs_to :<%= parent_association_name -%><%= ", :foreign_key => \"#{parent_association_name}_id\", :class_name => \"Comment\"" if options[:self_referential] %> + belongs_to :commentable, :polymorphic => true + + # This callback makes sure that an orphaned Comment is deleted if it no longer tags anything. + def before_destroy + <%= parent_association_name -%>.destroy_without_callbacks if <%= parent_association_name -%> and <%= parent_association_name -%>.commentings.count == 1 + end +end diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_extensions.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_extensions.rb new file mode 100644 index 0000000..346ab2a --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_extensions.rb @@ -0,0 +1,30 @@ +class ActiveRecord::Base + module CommentingExtensions + + def comment_count + commentable? + self.comments.size + end + + def comment_with(attributes) + commentable?(true) + begin + comment = Comment.create(attributes) + raise Comment::Error, "Comment could not be saved with" if comment.new_record? + comment.commentables << self + rescue + end + end + + private + def commentable?(should_raise = false) #:nodoc: + unless flag = respond_to?(:<%= parent_association_name -%>s) + raise "#{self.class} is not a commentable model" if should_raise + end + flag + end + end + + include CommentingExtensions +end + diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_test.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_test.rb new file mode 100644 index 0000000..37b9cb5 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commenting_test.rb @@ -0,0 +1,30 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class CommentingTest < Test::Unit::TestCase + fixtures :commentings, :comments, <%= commentable_models[0..1].join(", ") -%> + + def setup + @obj1 = <%= model_two %>.find(1) + @obj2 = <%= model_two %>.find(2) +<% if commentable_models.size > 1 -%> + @obj3 = <%= model_one -%>.find(1) +<% end -%> + @comment1 = Comment.find(1) + @comment2 = Comment.find(2) + @commenting1 = Commenting.find(1) + end + + def test_commentable + assert_raises(RuntimeError) do + @commenting1.send(:commentable?, true) + end + assert !@commenting1.send(:commentable?) +<% if commentable_models.size > 1 -%> + assert @obj3.send(:commentable?) +<% end -%> +<% if options[:self_referential] -%> + assert @comment1.send(:commentable?) +<% end -%> + end + +end diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commentings.yml b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commentings.yml new file mode 100644 index 0000000..39acd72 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/commentings.yml @@ -0,0 +1,23 @@ +--- +<% if commentable_models.size > 1 -%> +commentings_003: + <%= parent_association_name -%>_id: "2" + id: "3" + commentable_type: <%= model_one %> + commentable_id: "1" +<% end -%> +commentings_004: + <%= parent_association_name -%>_id: "2" + id: "4" + commentable_type: <%= model_two %> + commentable_id: "2" +commentings_001: + <%= parent_association_name -%>_id: "1" + id: "1" + commentable_type: <%= model_two %> + commentable_id: "1" +commentings_002: + <%= parent_association_name -%>_id: "1" + id: "2" + commentable_type: <%= model_two %> + commentable_id: "2" diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comments.yml b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comments.yml new file mode 100644 index 0000000..4a93735 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/comments.yml @@ -0,0 +1,13 @@ +--- +comments_001: + id: "1" + name: frivolous + email: no1@nowhere.com + url: http://fr.ivolo.us + body: this plugin rocks! +tags_002: + id: "2" + name: yuanyiz + email: no1@nowhere.com + url: http://letrails.cn + body: this plugin has saved my life diff --git a/vendor/plugins/has_many_polymorphs/generators/commenting/templates/migration.rb b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/migration.rb new file mode 100644 index 0000000..b8a86aa --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/commenting/templates/migration.rb @@ -0,0 +1,28 @@ + +# A migration to add tables for Comment and Commenting. This file is automatically generated and added to your app if you run the commenting generator. + +class CreateCommentsAndCommentings < ActiveRecord::Migration + + # Add the new tables. + def self.up + create_table :comments do |t| + t.column :name, :string, :null => false + t.column :url, :string + t.column :email, :string + t.column :body, :text + end + + create_table :commentings do |t| + t.column :<%= parent_association_name -%>_id, :integer, :null => false + t.column :commentable_id, :integer, :null => false + t.column :commentable_type, :string, :null => false + end + end + + # Remove the tables. + def self.down + drop_table :comments + drop_table :commentings + end + +end diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/tagging_generator.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/tagging_generator.rb new file mode 100644 index 0000000..31fb088 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/tagging/tagging_generator.rb @@ -0,0 +1,95 @@ +require 'ruby-debug' and Debugger.start if ENV['USER'] == 'eweaver' + +class TaggingGenerator < Rails::Generator::NamedBase + default_options :skip_migration => false + default_options :self_referential => false + attr_reader :parent_association_name + attr_reader :taggable_models + + def initialize(runtime_args, runtime_options = {}) + @parent_association_name = (runtime_args.include?("--self-referential") ? "tagger" : "tag") + @taggable_models = runtime_args.reject{|opt| opt =~ /^--/}.map do |taggable| + ":" + taggable.underscore.pluralize + end + @taggable_models += [":tags"] if runtime_args.include?("--self-referential") + @taggable_models.uniq! + + verify @taggable_models + hacks + runtime_args.unshift("placeholder") + super + end + + def verify models + puts "** Warning: only one taggable model specified; tests may not run properly." if models.size < 2 + models.each do |model| + model = model[1..-1].classify + next if model == "Tag" # don't load ourselves when --self-referential is used + self.class.const_get(model) rescue puts "** Error: model #{model[1..-1].classify} could not be loaded." or exit + end + end + + def hacks + # add the extension require in environment.rb + phrase = "require 'tagging_extensions'" + filename = "#{RAILS_ROOT}/config/environment.rb" + unless (open(filename) do |file| + file.grep(/#{Regexp.escape phrase}/).any? + end) + open(filename, 'a+') do |file| + file.puts "\n" + phrase + "\n" + end + end + end + + def manifest + record do |m| + m.class_collisions class_path, class_name, "#{class_name}Test" + + m.directory File.join('app/models', class_path) + m.directory File.join('test/unit', class_path) + m.directory File.join('test/fixtures', class_path) + m.directory File.join('test/fixtures', class_path) + m.directory File.join('lib') + + m.template 'tag.rb', File.join('app/models', class_path, "tag.rb") + m.template 'tag_test.rb', File.join('test/unit', class_path, "tag_test.rb") + m.template 'tags.yml', File.join('test/fixtures', class_path, "tags.yml") + + m.template 'tagging.rb', File.join('app/models', class_path, "tagging.rb") + m.template 'tagging_test.rb', File.join('test/unit', class_path, "tagging_test.rb") + m.template 'taggings.yml', File.join('test/fixtures', class_path, "taggings.yml") + + m.template 'tagging_extensions.rb', File.join('lib', 'tagging_extensions.rb') + + unless options[:skip_migration] + m.migration_template 'migration.rb', 'db/migrate', + :migration_file_name => "create_tags_and_taggings" + end + + end + end + + protected + def banner + "Usage: #{$0} generate tagging [TaggableModelA TaggableModelB ...]" + end + + def add_options!(opt) + opt.separator '' + opt.separator 'Options:' + opt.on("--skip-migration", + "Don't generate a migration file for this model") { |v| options[:skip_migration] = v } + opt.on("--self-referential", + "Allow tags to tag themselves.") { |v| options[:self_referential] = v } + end + + # Useful for generating tests/fixtures + def model_one + taggable_models[0][1..-1].classify + end + + def model_two + taggable_models[1][1..-1].classify rescue model_one + end +end diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/migration.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/migration.rb new file mode 100644 index 0000000..582b54c --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/migration.rb @@ -0,0 +1,28 @@ + +# A migration to add tables for Tag and Tagging. This file is automatically generated and added to your app if you run the tagging generator included with has_many_polymorphs. + +class CreateTagsAndTaggings < ActiveRecord::Migration + + # Add the new tables. + def self.up + create_table :tags do |t| + t.column :name, :string, :null => false + end + add_index :tags, :name, :unique => true + + create_table :taggings do |t| + t.column :<%= parent_association_name -%>_id, :integer, :null => false + t.column :taggable_id, :integer, :null => false + t.column :taggable_type, :string, :null => false + # t.column :position, :integer # Uncomment this if you need to use acts_as_list. + end + add_index :taggings, [:<%= parent_association_name -%>_id, :taggable_id, :taggable_type], :unique => true + end + + # Remove the tables. + def self.down + drop_table :tags + drop_table :taggings + end + +end diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tag.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tag.rb new file mode 100644 index 0000000..1966a76 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tag.rb @@ -0,0 +1,39 @@ + +# The Tag model. This model is automatically generated and added to your app if you run the tagging generator included with has_many_polymorphs. + +class Tag < ActiveRecord::Base + + DELIMITER = " " # Controls how to split and join tagnames from strings. You may need to change the validates_format_of parameters if you change this. + + # If database speed becomes an issue, you could remove these validations and rescue the ActiveRecord database constraint errors instead. + validates_presence_of :name + validates_uniqueness_of :name, :case_sensitive => false + + # Change this validation if you need more complex tag names. + validates_format_of :name, :with => /^[a-zA-Z0-9\_\-]+$/, :message => "can not contain special characters" + + # Set up the polymorphic relationship. + has_many_polymorphs :taggables, + :from => [<%= taggable_models.join(", ") %>], + :through => :taggings, + :dependent => :destroy, +<% if options[:self_referential] -%> :as => :<%= parent_association_name -%>, +<% end -%> + :skip_duplicates => false, + :parent_extend => proc { + # Defined on the taggable models, not on Tag itself. Return the tagnames associated with this record as a string. + def to_s + self.map(&:name).sort.join(Tag::DELIMITER) + end + } + + # Callback to strip extra spaces from the tagname before saving it. If you allow tags to be renamed later, you might want to use the before_save callback instead. + def before_create + self.name = name.downcase.strip.squeeze(" ") + end + + # Tag::Error class. Raised by ActiveRecord::Base::TaggingExtensions if something goes wrong. + class Error < StandardError + end + +end diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tag_test.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tag_test.rb new file mode 100644 index 0000000..7cf39c6 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tag_test.rb @@ -0,0 +1,10 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class TagTest < Test::Unit::TestCase + fixtures :tags, :taggings, <%= taggable_models[0..1].join(", ") -%> + + def test_to_s + assert_equal "delicious sexy", <%= model_two -%>.find(2).tags.to_s + end + +end diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging.rb new file mode 100644 index 0000000..2cf4cee --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging.rb @@ -0,0 +1,16 @@ + +# The Tagging join model. This model is automatically generated and added to your app if you run the tagging generator included with has_many_polymorphs. + +class Tagging < ActiveRecord::Base + + belongs_to :<%= parent_association_name -%><%= ", :foreign_key => \"#{parent_association_name}_id\", :class_name => \"Tag\"" if options[:self_referential] %> + belongs_to :taggable, :polymorphic => true + + # If you also need to use acts_as_list, you will have to manage the tagging positions manually by creating decorated join records when you associate Tags with taggables. + # acts_as_list :scope => :taggable + + # This callback makes sure that an orphaned Tag is deleted if it no longer tags anything. + def before_destroy + <%= parent_association_name -%>.destroy_without_callbacks if <%= parent_association_name -%> and <%= parent_association_name -%>.taggings.count == 1 + end +end diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_extensions.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_extensions.rb new file mode 100644 index 0000000..2cc3dda --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_extensions.rb @@ -0,0 +1,106 @@ + +class ActiveRecord::Base #:nodoc: + + # These extensions make models taggable. This file is automatically generated and required by your app if you run the tagging generator included with has_many_polymorphs. + module TaggingExtensions + + # Add tags to self. Accepts a string of tagnames, an array of tagnames, an array of ids, or an array of Tags. + # + # We need to avoid name conflicts with the built-in ActiveRecord association methods, thus the underscores. + def _add_tags incoming + taggable?(true) + tag_cast_to_string(incoming).each do |tag_name| + begin + tag = Tag.find_or_create_by_name(tag_name) + raise Tag::Error, "tag could not be saved: #{tag_name}" if tag.new_record? + tag.taggables << self + rescue ActiveRecord::StatementInvalid => e + raise unless e.to_s =~ /duplicate/i + end + end + end + + # Removes tags from self. Accepts a string of tagnames, an array of tagnames, an array of ids, or an array of Tags. + def _remove_tags outgoing + taggable?(true) + outgoing = tag_cast_to_string(outgoing) + <% if options[:self_referential] %> + # because of http://dev.rubyonrails.org/ticket/6466 + taggings.destroy(*(taggings.find(:all, :include => :<%= parent_association_name -%>).select do |tagging| + outgoing.include? tagging.<%= parent_association_name -%>.name + end)) + <% else -%> + <%= parent_association_name -%>s.delete(*(<%= parent_association_name -%>s.select do |tag| + outgoing.include? tag.name + end)) + <% end -%> + end + + # Returns the tags on self as a string. + def tag_list + # Redefined later to avoid an RDoc parse error. + end + + # Replace the existing tags on self. Accepts a string of tagnames, an array of tagnames, an array of ids, or an array of Tags. + def tag_with list + #:stopdoc: + taggable?(true) + list = tag_cast_to_string(list) + + # Transactions may not be ideal for you here; be aware. + Tag.transaction do + current = <%= parent_association_name -%>s.map(&:name) + _add_tags(list - current) + _remove_tags(current - list) + end + + self + #:startdoc: + end + + # Returns the tags on self as a string. + def tag_list #:nodoc: + #:stopdoc: + taggable?(true) + <%= parent_association_name -%>s.reload + <%= parent_association_name -%>s.to_s + #:startdoc: + end + + private + + def tag_cast_to_string obj #:nodoc: + case obj + when Array + obj.map! do |item| + case item + when /^\d+$/, Fixnum then Tag.find(item).name # This will be slow if you use ids a lot. + when Tag then item.name + when String then item + else + raise "Invalid type" + end + end + when String + obj = obj.split(Tag::DELIMITER).map do |tag_name| + tag_name.strip.squeeze(" ") + end + else + raise "Invalid object of class #{obj.class} as tagging method parameter" + end.flatten.compact.map(&:downcase).uniq + end + + # Check if a model is in the :taggables target list. The alternative to this check is to explicitly include a TaggingMethods module (which you would create) in each target model. + def taggable?(should_raise = false) #:nodoc: + unless flag = respond_to?(:<%= parent_association_name -%>s) + raise "#{self.class} is not a taggable model" if should_raise + end + flag + end + + end + + include TaggingExtensions + +end + diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_test.rb b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_test.rb new file mode 100644 index 0000000..5740666 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tagging_test.rb @@ -0,0 +1,62 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class TaggingTest < Test::Unit::TestCase + fixtures :taggings, :tags, <%= taggable_models[0..1].join(", ") -%> + + def setup + @obj1 = <%= model_two %>.find(1) + @obj2 = <%= model_two %>.find(2) +<% if taggable_models.size > 1 -%> + @obj3 = <%= model_one -%>.find(1) +<% end -%> + @tag1 = Tag.find(1) + @tag2 = Tag.find(2) + @tagging1 = Tagging.find(1) + end + + def test_tag_with + @obj2.tag_with "dark columbian" + assert_equal "columbian dark", @obj2.tag_list + end + +<% if options[:self_referential] -%> + def test_self_referential_tag_with + @tag1.tag_with [1, 2] + assert @tag1.tags.include?(@tag1) + assert !@tag2.tags.include?(@tag1) + end + +<% end -%> + def test__add_tags + @obj1._add_tags "porter longneck" + assert Tag.find_by_name("porter").taggables.include?(@obj1) + assert Tag.find_by_name("longneck").taggables.include?(@obj1) + assert_equal "delicious longneck porter", @obj1.tag_list + + @obj1._add_tags [2] + assert_equal "delicious longneck porter sexy", @obj1.tag_list + end + + def test__remove_tags + @obj2._remove_tags ["2", @tag1] + assert @obj2.tags.empty? + end + + def test_tag_list + assert_equal "delicious sexy", @obj2.tag_list + end + + def test_taggable + assert_raises(RuntimeError) do + @tagging1.send(:taggable?, true) + end + assert !@tagging1.send(:taggable?) +<% if taggable_models.size > 1 -%> + assert @obj3.send(:taggable?) +<% end -%> +<% if options[:self_referential] -%> + assert @tag1.send(:taggable?) +<% end -%> + end + +end diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/taggings.yml b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/taggings.yml new file mode 100644 index 0000000..0cf13b9 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/taggings.yml @@ -0,0 +1,23 @@ +--- +<% if taggable_models.size > 1 -%> +taggings_003: + <%= parent_association_name -%>_id: "2" + id: "3" + taggable_type: <%= model_one %> + taggable_id: "1" +<% end -%> +taggings_004: + <%= parent_association_name -%>_id: "2" + id: "4" + taggable_type: <%= model_two %> + taggable_id: "2" +taggings_001: + <%= parent_association_name -%>_id: "1" + id: "1" + taggable_type: <%= model_two %> + taggable_id: "1" +taggings_002: + <%= parent_association_name -%>_id: "1" + id: "2" + taggable_type: <%= model_two %> + taggable_id: "2" diff --git a/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tags.yml b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tags.yml new file mode 100644 index 0000000..3bf1078 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/generators/tagging/templates/tags.yml @@ -0,0 +1,7 @@ +--- +tags_001: + name: delicious + id: "1" +tags_002: + name: sexy + id: "2" diff --git a/vendor/plugins/has_many_polymorphs/init.rb b/vendor/plugins/has_many_polymorphs/init.rb new file mode 100644 index 0000000..3939a25 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/init.rb @@ -0,0 +1,2 @@ + +require 'has_many_polymorphs' diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs.rb new file mode 100644 index 0000000..2df17d7 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs.rb @@ -0,0 +1,28 @@ + +require 'active_record' + +RAILS_DEFAULT_LOGGER = nil unless defined? RAILS_DEFAULT_LOGGER + +require 'has_many_polymorphs/reflection' +require 'has_many_polymorphs/association' +require 'has_many_polymorphs/class_methods' + +require 'has_many_polymorphs/support_methods' +require 'has_many_polymorphs/base' + +class ActiveRecord::Base + extend ActiveRecord::Associations::PolymorphicClassMethods +end + +if ENV['HMP_DEBUG'] or ENV['RAILS_ENV'] =~ /development|test/ and ENV['USER'] == 'eweaver' + require 'has_many_polymorphs/debugging_tools' +end + +if defined? Rails and RAILS_ENV and RAILS_ROOT + _logger_warn "rails environment detected" + require 'has_many_polymorphs/configuration' + require 'has_many_polymorphs/dependencies' + require 'has_many_polymorphs/autoload' +end + +_logger_debug "loaded ok" diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/association.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/association.rb new file mode 100644 index 0000000..a2b2d81 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/association.rb @@ -0,0 +1,159 @@ +module ActiveRecord #:nodoc: + module Associations #:nodoc: + + class PolymorphicError < ActiveRecordError #:nodoc: + end + + class PolymorphicMethodNotSupportedError < ActiveRecordError #:nodoc: + end + + # The association class for a has_many_polymorphs association. + class PolymorphicAssociation < HasManyThroughAssociation + + # Push a record onto the association. Triggers a database load for a uniqueness check only if :skip_duplicates is true. Return value is undefined. + def <<(*records) + return if records.empty? + + if @reflection.options[:skip_duplicates] + _logger_debug "Loading instances for polymorphic duplicate push check; use :skip_duplicates => false and perhaps a database constraint to avoid this possible performance issue" + load_target + end + + @reflection.klass.transaction do + flatten_deeper(records).each do |record| + if @owner.new_record? or not record.respond_to?(:new_record?) or record.new_record? + raise PolymorphicError, "You can't associate unsaved records." + end + next if @reflection.options[:skip_duplicates] and @target.include? record + @owner.send(@reflection.through_reflection.name).proxy_target << @reflection.klass.create!(construct_join_attributes(record)) + @target << record if loaded? + end + end + + self + end + + alias :push :<< + alias :concat :<< + + # Runs a find against the association contents, returning the matched records. All regular find options except :include are supported. + def find(*args) + opts = args._extract_options! + opts.delete :include + super(*(args + [opts])) + end + + def construct_scope + _logger_warn "Warning; not all usage scenarios for polymorphic scopes are supported yet." + super + end + + # Deletes a record from the association. Return value is undefined. + def delete(*records) + records = flatten_deeper(records) + records.reject! {|record| @target.delete(record) if record.new_record?} + return if records.empty? + + @reflection.klass.transaction do + records.each do |record| + joins = @reflection.through_reflection.name + @owner.send(joins).delete(@owner.send(joins).select do |join| + join.send(@reflection.options[:polymorphic_key]) == record.id and + join.send(@reflection.options[:polymorphic_type_key]) == "#{record.class.base_class}" + end) + @target.delete(record) + end + end + end + + # Clears all records from the association. Returns an empty array. + def clear(klass = nil) + load_target + return if @target.empty? + + if klass + delete(@target.select {|r| r.is_a? klass }) + else + @owner.send(@reflection.through_reflection.name).clear + @target.clear + end + [] + end + + protected + +# undef :sum +# undef :create! + + def construct_quoted_owner_attributes(*args) #:nodoc: + # no access to returning() here? why not? + type_key = @reflection.options[:foreign_type_key] + {@reflection.primary_key_name => @owner.id, + type_key=> (@owner.class.base_class.name if type_key)} + end + + def construct_from #:nodoc: + # build the FROM part of the query, in this case, the polymorphic join table + @reflection.klass.table_name + end + + def construct_owner #:nodoc: + # the table name for the owner object's class + @owner.class.table_name + end + + def construct_owner_key #:nodoc: + # the primary key field for the owner object + @owner.class.primary_key + end + + def construct_select(custom_select = nil) #:nodoc: + # build the select query + selected = custom_select || @reflection.options[:select] + end + + def construct_joins(custom_joins = nil) #:nodoc: + # build the string of default joins + "JOIN #{construct_owner} polymorphic_parent ON #{construct_from}.#{@reflection.options[:foreign_key]} = polymorphic_parent.#{construct_owner_key} " + + @reflection.options[:from].map do |plural| + klass = plural._as_class + "LEFT JOIN #{klass.table_name} ON #{construct_from}.#{@reflection.options[:polymorphic_key]} = #{klass.table_name}.#{klass.primary_key} AND #{construct_from}.#{@reflection.options[:polymorphic_type_key]} = #{@reflection.klass.quote_value(klass.base_class.name)}" + end.uniq.join(" ") + " #{custom_joins}" + end + + def construct_conditions #:nodoc: + # build the fully realized condition string + conditions = construct_quoted_owner_attributes.map do |field, value| + "#{construct_from}.#{field} = #{@reflection.klass.quote_value(value)}" if value + end + conditions << custom_conditions if custom_conditions + "(" + conditions.compact.join(') AND (') + ")" + end + + def custom_conditions #:nodoc: + # custom conditions... not as messy as has_many :through because our joins are a little smarter + if @reflection.options[:conditions] + "(" + interpolate_sql(@reflection.klass.send(:sanitize_sql, @reflection.options[:conditions])) + ")" + end + end + + alias :construct_owner_attributes :construct_quoted_owner_attributes + alias :conditions :custom_conditions # XXX possibly not necessary + alias :sql_conditions :custom_conditions # XXX ditto + + # construct attributes for join for a particular record + def construct_join_attributes(record) #:nodoc: + {@reflection.options[:polymorphic_key] => record.id, + @reflection.options[:polymorphic_type_key] => "#{record.class.base_class}", + @reflection.options[:foreign_key] => @owner.id}.merge(@reflection.options[:foreign_type_key] ? + {@reflection.options[:foreign_type_key] => "#{@owner.class.base_class}"} : {}) # for double-sided relationships + end + + def build(attrs = nil) #:nodoc: + raise PolymorphicMethodNotSupportedError, "You can't associate new records." + end + + end + + end +end diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/autoload.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/autoload.rb new file mode 100644 index 0000000..ccee4cd --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/autoload.rb @@ -0,0 +1,62 @@ + +require 'initializer' unless defined? Rails::Initializer + +class Rails::Initializer #:nodoc: + +=begin rdoc +Searches for models that use has_many_polymorphs or acts_as_double_polymorphic_join and makes sure that they get loaded during app initialization. This ensures that helper methods are injected into the target classes. + +Note that you can override DEFAULT_OPTIONS via Rails::Configuration#has_many_polymorphs_options. For example, if you need an application extension to be required before has_many_polymorphs loads your models, add an after_initialize block in config/environment.rb that appends to the 'requirements' key: + Rails::Initializer.run do |config| + # your other configuration here + + config.after_initialize do + config.has_many_polymorphs_options['requirements'] << '/lib/my_extension' + end + end + +=end + + module HasManyPolymorphsAutoload + + DEFAULT_OPTIONS = { + :file_pattern => "#{RAILS_ROOT}/app/models/**/*.rb", + :file_exclusions => ['svn', 'CVS', 'bzr'], + :methods => ['has_many_polymorphs', 'acts_as_double_polymorphic_join'], + :requirements => []} + + mattr_accessor :options + @@options = HashWithIndifferentAccess.new(DEFAULT_OPTIONS) + + # Override for Rails::Initializer#after_initialize. + def after_initialize_with_autoload + after_initialize_without_autoload + + _logger_debug "autoload hook invoked" + + HasManyPolymorphsAutoload.options[:requirements].each do |requirement| + require requirement + end + + Dir[HasManyPolymorphsAutoload.options[:file_pattern]].each do |filename| + next if filename =~ /#{HasManyPolymorphsAutoload.options[:file_exclusions].join("|")}/ + open filename do |file| + if file.grep(/#{HasManyPolymorphsAutoload.options[:methods].join("|")}/).any? + begin + model = File.basename(filename)[0..-4].camelize + _logger_warn "preloading parent model #{model}" + model.constantize + rescue Object => e + _logger_warn "WARNING; possibly critical error preloading #{model}: #{e.inspect}" + end + end + end + end + end + + end + + include HasManyPolymorphsAutoload + + alias_method_chain :after_initialize, :autoload +end diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/base.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/base.rb new file mode 100644 index 0000000..9513039 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/base.rb @@ -0,0 +1,60 @@ + +module ActiveRecord + class Base + + class << self + + # Interprets a polymorphic row from a unified SELECT, returning the appropriate ActiveRecord instance. Overrides ActiveRecord::Base.instantiate_without_callbacks. + def instantiate_with_polymorphic_checks(record) + if record['polymorphic_parent_class'] + reflection = record['polymorphic_parent_class'].constantize.reflect_on_association(record['polymorphic_association_id'].to_sym) +# _logger_debug "Instantiating a polymorphic row for #{record['polymorphic_parent_class']}.reflect_on_association(:#{record['polymorphic_association_id']})" + + # rewrite the record with the right column names + table_aliases = reflection.options[:table_aliases].dup + record = Hash[*table_aliases.keys.map {|key| [key, record[table_aliases[key]]] }.flatten] + + # find the real child class + klass = record["#{self.table_name}.#{reflection.options[:polymorphic_type_key]}"].constantize + if sti_klass = record["#{klass.table_name}.#{klass.inheritance_column}"] + klass = klass.class_eval do compute_type(sti_klass) end # in case of namespaced STI models + end + + # check that the join actually joined to something + unless (child_id = record["#{self.table_name}.#{reflection.options[:polymorphic_key]}"]) == record["#{klass.table_name}.#{klass.primary_key}"] + raise ActiveRecord::Associations::PolymorphicError, + "Referential integrity violation; child <#{klass.name}:#{child_id}> was not found for #{reflection.name.inspect}" + end + + # eject the join keys + # XXX not very readable + record = Hash[*record._select do |column, value| + column[/^#{klass.table_name}/] + end.map do |column, value| + [column[/\.(.*)/, 1], value] + end.flatten] + + # allocate and assign values + returning(klass.allocate) do |obj| + obj.instance_variable_set("@attributes", record) + obj.instance_variable_set("@attributes_cache", Hash.new) + + if obj.respond_to_without_attributes?(:after_find) + obj.send(:callback, :after_find) + end + + if obj.respond_to_without_attributes?(:after_initialize) + obj.send(:callback, :after_initialize) + end + + end + else + instantiate_without_polymorphic_checks(record) + end + end + + alias_method_chain :instantiate, :polymorphic_checks + end + + end +end diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/class_methods.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/class_methods.rb new file mode 100644 index 0000000..a830f63 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/class_methods.rb @@ -0,0 +1,609 @@ + +module ActiveRecord #:nodoc: + module Associations #:nodoc: + +=begin rdoc + +Class methods added to ActiveRecord::Base for setting up polymorphic associations. + +== Notes + +STI association targets must enumerated and named. For example, if Dog and Cat both inherit from Animal, you still need to say [:dogs, :cats], and not [:animals]. + +Namespaced models follow the Rails underscore convention. ZooAnimal::Lion becomes :'zoo_animal/lion'. + +You do not need to set up any other associations other than for either the regular method or the double. The join associations and all individual and reverse associations are generated for you. However, a join model and table are required. + +There is a tentative report that you can make the parent model be its own join model, but this is untested. + +=end + + module PolymorphicClassMethods + + RESERVED_DOUBLES_KEYS = [:conditions, :order, :limit, :offset, :extend, :skip_duplicates, + :join_extend, :dependent, :rename_individual_collections, + :namespace] #:nodoc: + +=begin rdoc + +This method creates a doubled-sided polymorphic relationship. It must be called on the join model: + + class Devouring < ActiveRecord::Base + belongs_to :eater, :polymorphic => true + belongs_to :eaten, :polymorphic => true + + acts_as_double_polymorphic_join( + :eaters => [:dogs, :cats], + :eatens => [:cats, :birds] + ) + end + +The method works by defining one or more special has_many_polymorphs association on every model in the target lists, depending on which side of the association it is on. Double self-references will work. + +The two association names and their value arrays are the only required parameters. + +== Available options + +These options are passed through to targets on both sides of the association. If you want to affect only one side, prepend the key with the name of that side. For example, :eaters_extend. + +:dependent:: Accepts :destroy, :nullify, or :delete_all. Controls how the join record gets treated on any association delete (whether from the polymorph or from an individual collection); defaults to :destroy. +:skip_duplicates:: If true, will check to avoid pushing already associated records (but also triggering a database load). Defaults to true. +:rename_individual_collections:: If true, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with "\_of_#{association_name}". +:extend:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods). +:join_extend:: One or an array of mixed modules and procs, which are applied to the join association. +:conditions:: An array or string of conditions for the SQL WHERE clause. +:order:: A string for the SQL ORDER BY clause. +:limit:: An integer. Affects the polymorphic and individual associations. +:offset:: An integer. Only affects the polymorphic association. +:namespace:: A symbol. Prepended to all the models in the :from and :through keys. This is especially useful for Camping, which namespaces models by default. + +=end + + def acts_as_double_polymorphic_join options={}, &extension + + collections, options = extract_double_collections(options) + + # handle the block + options[:extend] = (if options[:extend] + Array(options[:extend]) + [extension] + else + extension + end) if extension + + collection_option_keys = make_general_option_keys_specific!(options, collections) + + join_name = self.name.tableize.to_sym + collections.each do |association_id, children| + parent_hash_key = (collections.keys - [association_id]).first # parents are the entries in the _other_ children array + + begin + parent_foreign_key = self.reflect_on_association(parent_hash_key._singularize).primary_key_name + rescue NoMethodError + raise PolymorphicError, "Couldn't find 'belongs_to' association for :#{parent_hash_key._singularize} in #{self.name}." unless parent_foreign_key + end + + parents = collections[parent_hash_key] + conflicts = (children & parents) # set intersection + parents.each do |plural_parent_name| + + parent_class = plural_parent_name._as_class + singular_reverse_association_id = parent_hash_key._singularize + + internal_options = { + :is_double => true, + :from => children, + :as => singular_reverse_association_id, + :through => join_name.to_sym, + :foreign_key => parent_foreign_key, + :foreign_type_key => parent_foreign_key.to_s.sub(/_id$/, '_type'), + :singular_reverse_association_id => singular_reverse_association_id, + :conflicts => conflicts + } + + general_options = Hash[*options._select do |key, value| + collection_option_keys[association_id].include? key and !value.nil? + end.map do |key, value| + [key.to_s[association_id.to_s.length+1..-1].to_sym, value] + end._flatten_once] # rename side-specific options to general names + + general_options.each do |key, value| + # avoid clobbering keys that appear in both option sets + if internal_options[key] + general_options[key] = Array(value) + Array(internal_options[key]) + end + end + + parent_class.send(:has_many_polymorphs, association_id, internal_options.merge(general_options)) + + if conflicts.include? plural_parent_name + # unify the alternate sides of the conflicting children + (conflicts).each do |method_name| + unless parent_class.instance_methods.include?(method_name) + parent_class.send(:define_method, method_name) do + (self.send("#{singular_reverse_association_id}_#{method_name}") + + self.send("#{association_id._singularize}_#{method_name}")).freeze + end + end + end + + # unify the join model... join model is always renamed for doubles, unlike child associations + unless parent_class.instance_methods.include?(join_name) + parent_class.send(:define_method, join_name) do + (self.send("#{join_name}_as_#{singular_reverse_association_id}") + + self.send("#{join_name}_as_#{association_id._singularize}")).freeze + end + end + else + unless parent_class.instance_methods.include?(join_name) + parent_class.send(:alias_method, join_name, "#{join_name}_as_#{singular_reverse_association_id}") + end + end + + end + end + end + + private + + def extract_double_collections(options) + collections = options._select do |key, value| + value.is_a? Array and key.to_s !~ /(#{RESERVED_DOUBLES_KEYS.map(&:to_s).join('|')})$/ + end + + raise PolymorphicError, "Couldn't understand options in acts_as_double_polymorphic_join. Valid parameters are your two class collections, and then #{RESERVED_DOUBLES_KEYS.inspect[1..-2]}, with optionally your collection names prepended and joined with an underscore." unless collections.size == 2 + + options = options._select do |key, value| + !collections[key] + end + + [collections, options] + end + + def make_general_option_keys_specific!(options, collections) + collection_option_keys = Hash[*collections.keys.map do |key| + [key, RESERVED_DOUBLES_KEYS.map{|option| "#{key}_#{option}".to_sym}] + end._flatten_once] + + collections.keys.each do |collection| + options.each do |key, value| + next if collection_option_keys.values.flatten.include? key + # shift the general options to the individual sides + collection_key = "#{collection}_#{key}".to_sym + collection_value = options[collection_key] + case key + when :conditions + collection_value, value = sanitize_sql(collection_value), sanitize_sql(value) + options[collection_key] = (collection_value ? "(#{collection_value}) AND (#{value})" : value) + when :order + options[collection_key] = (collection_value ? "#{collection_value}, #{value}" : value) + when :extend, :join_extend + options[collection_key] = Array(collection_value) + Array(value) + else + options[collection_key] ||= value + end + end + end + + collection_option_keys + end + + + + public + +=begin rdoc + +This method createds a single-sided polymorphic relationship. + + class Petfood < ActiveRecord::Base + has_many_polymorphs :eaters, :from => [:dogs, :cats, :birds] + end + +The only required parameter, aside from the association name, is :from. + +The method generates a number of associations aside from the polymorphic one. In this example Petfood also gets dogs, cats, and birds, and Dog, Cat, and Bird get petfoods. (The reverse association to the parents is always plural.) + +== Available options + +:from:: An array of symbols representing the target models. Required. +:as:: A symbol for the parent's interface in the join--what the parent 'acts as'. +:through:: A symbol representing the class of the join model. Follows Rails defaults if not supplied (the parent and the association names, alphabetized, concatenated with an underscore, and singularized). +:dependent:: Accepts :destroy, :nullify, :delete_all. Controls how the join record gets treated on any associate delete (whether from the polymorph or from an individual collection); defaults to :destroy. +:skip_duplicates:: If true, will check to avoid pushing already associated records (but also triggering a database load). Defaults to true. +:rename_individual_collections:: If true, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with "_of_#{association_name}". For example, zoos becomes zoos_of_animals. This is to help avoid method name collisions in crowded classes. +:extend:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods). +:join_extend:: One or an array of mixed modules and procs, which are applied to the join association. +:parent_extend:: One or an array of mixed modules and procs, which are applied to the target models' association to the parents. +:conditions:: An array or string of conditions for the SQL WHERE clause. +:parent_conditions:: An array or string of conditions which are applied to the target models' association to the parents. +:order:: A string for the SQL ORDER BY clause. +:parent_order:: A string for the SQL ORDER BY which is applied to the target models' association to the parents. +:group:: An array or string of conditions for the SQL GROUP BY clause. Affects the polymorphic and individual associations. +:limit:: An integer. Affects the polymorphic and individual associations. +:offset:: An integer. Only affects the polymorphic association. +:namespace:: A symbol. Prepended to all the models in the :from and :through keys. This is especially useful for Camping, which namespaces models by default. +:uniq:: If true, the records returned are passed through a pure-Ruby uniq before they are returned. Rarely needed. +:foreign_key:: The column name for the parent's id in the join. +:foreign_type_key:: The column name for the parent's class name in the join, if the parent itself is polymorphic. Rarely needed--if you're thinking about using this, you almost certainly want to use acts_as_double_polymorphic_join() instead. +:polymorphic_key:: The column name for the child's id in the join. +:polymorphic_type_key:: The column name for the child's class name in the join. + +If you pass a block, it gets converted to a Proc and added to :extend. + +== On condition nullification + +When you request an individual association, non-applicable but fully-qualified fields in the polymorphic association's :conditions, :order, and :group options get changed to NULL. For example, if you set :conditions => "dogs.name != 'Spot'", when you request .cats, the conditions string is changed to NULL != 'Spot'. + +Be aware, however, that NULL != 'Spot' returns false due to SQL's 3-value logic. Instead, you need to use the :conditions string "dogs.name IS NULL OR dogs.name != 'Spot'" to get the behavior you probably expect for negative matches. + +=end + + def has_many_polymorphs (association_id, options = {}, &extension) + _logger_debug "associating #{self}.#{association_id}" + reflection = create_has_many_polymorphs_reflection(association_id, options, &extension) + # puts "Created reflection #{reflection.inspect}" + # configure_dependency_for_has_many(reflection) + collection_reader_method(reflection, PolymorphicAssociation) + end + + # Composed method that assigns option defaults, builds the reflection object, and sets up all the related associations on the parent, join, and targets. + def create_has_many_polymorphs_reflection(association_id, options, &extension) #:nodoc: + options.assert_valid_keys( + :from, + :as, + :through, + :foreign_key, + :foreign_type_key, + :polymorphic_key, # same as :association_foreign_key + :polymorphic_type_key, + :dependent, # default :destroy, only affects the join table + :skip_duplicates, # default true, only affects the polymorphic collection + :ignore_duplicates, # deprecated + :is_double, + :rename_individual_collections, + :reverse_association_id, # not used + :singular_reverse_association_id, + :conflicts, + :extend, + :join_class_name, + :join_extend, + :parent_extend, + :table_aliases, + :select, # applies to the polymorphic relationship + :conditions, # applies to the polymorphic relationship, the children, and the join + # :include, + :parent_conditions, + :parent_order, + :order, # applies to the polymorphic relationship, the children, and the join + :group, # only applies to the polymorphic relationship and the children + :limit, # only applies to the polymorphic relationship and the children + :offset, # only applies to the polymorphic relationship + :parent_order, + :parent_group, + :parent_limit, + :parent_offset, + # :source, + :namespace, + :uniq, # XXX untested, only applies to the polymorphic relationship + # :finder_sql, + # :counter_sql, + # :before_add, + # :after_add, + # :before_remove, + # :after_remove + :dummy) + + # validate against the most frequent configuration mistakes + verify_pluralization_of(association_id) + raise PolymorphicError, ":from option must be an array" unless options[:from].is_a? Array + options[:from].each{|plural| verify_pluralization_of(plural)} + + options[:as] ||= self.name.demodulize.underscore.to_sym + options[:conflicts] = Array(options[:conflicts]) + options[:foreign_key] ||= "#{options[:as]}_id" + + options[:association_foreign_key] = + options[:polymorphic_key] ||= "#{association_id._singularize}_id" + options[:polymorphic_type_key] ||= "#{association_id._singularize}_type" + + if options.has_key? :ignore_duplicates + _logger_warn "DEPRECATION WARNING: please use :skip_duplicates instead of :ignore_duplicates" + options[:skip_duplicates] = options[:ignore_duplicates] + end + options[:skip_duplicates] = true unless options.has_key? :skip_duplicates + options[:dependent] = :destroy unless options.has_key? :dependent + options[:conditions] = sanitize_sql(options[:conditions]) + + # options[:finder_sql] ||= "(options[:polymorphic_key] + + options[:through] ||= build_join_table_symbol(association_id, (options[:as]._pluralize or self.table_name)) + + # set up namespaces if we have a namespace key + # XXX needs test coverage + if options[:namespace] + namespace = options[:namespace].to_s.chomp("/") + "/" + options[:from].map! do |child| + "#{namespace}#{child}".to_sym + end + options[:through] = "#{namespace}#{options[:through]}".to_sym + end + + options[:join_class_name] ||= options[:through]._classify + options[:table_aliases] ||= build_table_aliases([options[:through]] + options[:from]) + options[:select] ||= build_select(association_id, options[:table_aliases]) + + options[:through] = "#{options[:through]}_as_#{options[:singular_reverse_association_id]}" if options[:singular_reverse_association_id] + options[:through] = demodulate(options[:through]).to_sym + + options[:extend] = spiked_create_extension_module(association_id, Array(options[:extend]) + Array(extension)) + options[:join_extend] = spiked_create_extension_module(association_id, Array(options[:join_extend]), "Join") + options[:parent_extend] = spiked_create_extension_module(association_id, Array(options[:parent_extend]), "Parent") + + # create the reflection object + returning(create_reflection(:has_many_polymorphs, association_id, options, self)) do |reflection| + if defined? Dependencies and defined? RAILS_ENV and RAILS_ENV == "development" + inject_dependencies(association_id, reflection) if Dependencies.mechanism == :load + end + + # set up the other related associations + create_join_association(association_id, reflection) + create_has_many_through_associations_for_parent_to_children(association_id, reflection) + create_has_many_through_associations_for_children_to_parent(association_id, reflection) + end + end + + private + + + # table mapping for use at the instantiation point + + def build_table_aliases(from) + # for the targets + returning({}) do |aliases| + from.map(&:to_s).sort.map(&:to_sym).each_with_index do |plural, t_index| + begin + table = plural._as_class.table_name + rescue NameError => e + raise PolymorphicError, "Could not find a valid class for #{plural.inspect}. If it's namespaced, be sure to specify it as :\"module/#{plural}\" instead." + end + plural._as_class.columns.map(&:name).each_with_index do |field, f_index| + aliases["#{table}.#{field}"] = "t#{t_index}_r#{f_index}" + end + end + end + end + + def build_select(association_id, aliases) + # instantiate has to know which reflection the results are coming from + (["\'#{self.name}\' AS polymorphic_parent_class", + "\'#{association_id}\' AS polymorphic_association_id"] + + aliases.map do |table, _alias| + "#{table} AS #{_alias}" + end.sort).join(", ") + end + + # model caching + def inject_dependencies(association_id, reflection) + _logger_debug "injecting dependencies" + requirements = [self, reflection.klass].map{|klass| [klass, klass.base_class]}.flatten.uniq + (all_classes_for(association_id, reflection) - requirements).each do |target_klass| + Dependencies.inject_dependency(target_klass, *requirements) + end + end + + # method sub-builders + + def create_join_association(association_id, reflection) + + options = { + :foreign_key => reflection.options[:foreign_key], + :dependent => reflection.options[:dependent], + :class_name => reflection.klass.name, + :extend => reflection.options[:join_extend] + # :limit => reflection.options[:limit], + # :offset => reflection.options[:offset], + # :order => devolve(association_id, reflection, reflection.options[:order], reflection.klass, true), + # :conditions => devolve(association_id, reflection, reflection.options[:conditions], reflection.klass, true) + } + + if reflection.options[:foreign_type_key] + type_check = "#{reflection.options[:foreign_type_key]} = #{quote_value(self.base_class.name)}" + conjunction = options[:conditions] ? " AND " : nil + options[:conditions] = "#{options[:conditions]}#{conjunction}#{type_check}" + options[:as] = reflection.options[:as] + end + + has_many(reflection.options[:through], options) + + inject_before_save_into_join_table(association_id, reflection) + end + + def inject_before_save_into_join_table(association_id, reflection) + sti_hook = "sti_class_rewrite" + rewrite_procedure = %[self.send(:#{reflection.options[:polymorphic_type_key]}=, self.#{reflection.options[:polymorphic_type_key]}.constantize.base_class.name)] + + # XXX should be abstracted? + reflection.klass.class_eval %[ + unless instance_methods.include? "before_save_with_#{sti_hook}" + if instance_methods.include? "before_save" + alias_method :before_save_without_#{sti_hook}, :before_save + def before_save_with_#{sti_hook} + before_save_without_#{sti_hook} + #{rewrite_procedure} + end + else + def before_save_with_#{sti_hook} + #{rewrite_procedure} + end + end + alias_method :before_save, :before_save_with_#{sti_hook} + end + ] + end + + def create_has_many_through_associations_for_children_to_parent(association_id, reflection) + + child_pluralization_map(association_id, reflection).each do |plural, singular| + if singular == reflection.options[:as] + raise PolymorphicError, if reflection.options[:is_double] + "You can't give either of the sides in a double-polymorphic join the same name as any of the individual target classes." + else + "You can't have a self-referential polymorphic has_many :through without renaming the non-polymorphic foreign key in the join model." + end + end + + parent = self + plural._as_class.instance_eval do + # this shouldn't be called at all during doubles; there is no way to traverse to a double polymorphic parent (XXX is that right?) + unless reflection.options[:is_double] or reflection.options[:conflicts].include? self.name.tableize.to_sym + + # the join table + through = "#{reflection.options[:through]}#{'_as_child' if parent == self}".to_sym + has_many(through, + :as => association_id._singularize, +# :source => association_id._singularize, +# :source_type => reflection.options[:polymorphic_type_key], + :class_name => reflection.klass.name, + :dependent => reflection.options[:dependent], + :extend => reflection.options[:join_extend], + # :limit => reflection.options[:limit], + # :offset => reflection.options[:offset], + :order => devolve(association_id, reflection, reflection.options[:parent_order], reflection.klass), + :conditions => devolve(association_id, reflection, reflection.options[:parent_conditions], reflection.klass) + ) + + # the association to the target's parents + association = "#{reflection.options[:as]._pluralize}#{"_of_#{association_id}" if reflection.options[:rename_individual_collections]}".to_sym + has_many(association, + :through => through, + :class_name => parent.name, + :source => reflection.options[:as], + :foreign_key => reflection.options[:foreign_key], + :extend => reflection.options[:parent_extend], + :conditions => reflection.options[:parent_conditions], + :order => reflection.options[:parent_order], + :offset => reflection.options[:parent_offset], + :limit => reflection.options[:parent_limit], + :group => reflection.options[:parent_group]) + +# debugger if association == :parents +# +# nil + + end + end + end + end + + def create_has_many_through_associations_for_parent_to_children(association_id, reflection) + child_pluralization_map(association_id, reflection).each do |plural, singular| + #puts ":source => #{child}" + current_association = demodulate(child_association_map(association_id, reflection)[plural]) + source = demodulate(singular) + + if reflection.options[:conflicts].include? plural + # XXX check this + current_association = "#{association_id._singularize}_#{current_association}" if reflection.options[:conflicts].include? self.name.tableize.to_sym + source = "#{source}_as_#{association_id._singularize}".to_sym + end + + # make push/delete accessible from the individual collections but still operate via the general collection + extension_module = self.class_eval %[ + module #{self.name + current_association._classify + "PolymorphicChildAssociationExtension"} + def push *args; proxy_owner.send(:#{association_id}).send(:push, *args); self; end + alias :<< :push + def delete *args; proxy_owner.send(:#{association_id}).send(:delete, *args); end + def clear; proxy_owner.send(:#{association_id}).send(:clear, #{singular._classify}); end + self + end] + + has_many(current_association.to_sym, + :through => reflection.options[:through], + :source => association_id._singularize, + :source_type => plural._as_class.base_class.name, + :class_name => plural._as_class.name, # make STI not conflate subtypes + :extend => (Array(extension_module) + reflection.options[:extend]), + :limit => reflection.options[:limit], + # :offset => reflection.options[:offset], + :order => devolve(association_id, reflection, reflection.options[:order], plural._as_class), + :conditions => devolve(association_id, reflection, reflection.options[:conditions], plural._as_class), + :group => devolve(association_id, reflection, reflection.options[:group], plural._as_class) + ) + + end + end + + # some support methods + + def child_pluralization_map(association_id, reflection) + Hash[*reflection.options[:from].map do |plural| + [plural, plural._singularize] + end.flatten] + end + + def child_association_map(association_id, reflection) + Hash[*reflection.options[:from].map do |plural| + [plural, "#{association_id._singularize.to_s + "_" if reflection.options[:rename_individual_collections]}#{plural}".to_sym] + end.flatten] + end + + def demodulate(s) + s.to_s.gsub('/', '_').to_sym + end + + def build_join_table_symbol(association_id, name) + [name.to_s, association_id.to_s].sort.join("_").to_sym + end + + def all_classes_for(association_id, reflection) + klasses = [self, reflection.klass, *child_pluralization_map(association_id, reflection).keys.map(&:_as_class)] + klasses += klasses.map(&:base_class) + klasses.uniq + end + + def devolve(association_id, reflection, string, klass, remove_inappropriate_clauses = false) + # XXX remove_inappropriate_clauses is not implemented; we'll wait until someone actually needs it + return unless string + string = string.dup + # _logger_debug "devolving #{string} for #{klass}" + inappropriate_classes = (all_classes_for(association_id, reflection) - # the join class must always be preserved + [klass, klass.base_class, reflection.klass, reflection.klass.base_class]) + inappropriate_classes.map do |klass| + klass.columns.map do |column| + [klass.table_name, column.name] + end.map do |table, column| + ["#{table}.#{column}", "`#{table}`.#{column}", "#{table}.`#{column}`", "`#{table}`.`#{column}`"] + end + end.flatten.sort_by(&:size).reverse.each do |quoted_reference| + # _logger_debug "devolved #{quoted_reference} to NULL" + # XXX clause removal would go here + string.gsub!(quoted_reference, "NULL") + end + # _logger_debug "altered to #{string}" + string + end + + def verify_pluralization_of(sym) + sym = sym.to_s + singular = sym.singularize + plural = singular.pluralize + raise PolymorphicError, "Pluralization rules not set up correctly. You passed :#{sym}, which singularizes to :#{singular}, but that pluralizes to :#{plural}, which is different. Maybe you meant :#{plural} to begin with?" unless sym == plural + end + + def spiked_create_extension_module(association_id, extensions, identifier = nil) + module_extensions = extensions.select{|e| e.is_a? Module} + proc_extensions = extensions.select{|e| e.is_a? Proc } + + # support namespaced anonymous blocks as well as multiple procs + proc_extensions.each_with_index do |proc_extension, index| + module_name = "#{self.to_s}#{association_id._classify}Polymorphic#{identifier}AssociationExtension#{index}" + the_module = self.class_eval "module #{module_name}; self; end" # XXX hrm + the_module.class_eval &proc_extension + module_extensions << the_module + end + module_extensions + end + + end + end +end diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/configuration.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/configuration.rb new file mode 100644 index 0000000..0059a3e --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/configuration.rb @@ -0,0 +1,17 @@ + +=begin rdoc +Access the has_many_polymorphs_options hash in your Rails::Initializer.run#after_initialize block if you need to modify the behavior of Rails::Initializer::HasManyPolymorphsAutoload. +=end + +class Rails::Configuration + + def has_many_polymorphs_options + Rails::Initializer::HasManyPolymorphsAutoload.options + end + + def has_many_polymorphs_options=(hash) + Rails::Initializer::HasManyPolymorphsAutoload.options = hash + end + +end + diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/debugging_tools.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/debugging_tools.rb new file mode 100644 index 0000000..22c9af3 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/debugging_tools.rb @@ -0,0 +1,103 @@ + +=begin rdoc + +Debugging tools for Has_many_polymorphs. + +Enable the different tools by setting the environment variable HMP_DEBUG. Settings with special meaning are "ruby-debug", "trace", and "dependencies". + +== Code generation + +Enabled by default when HMP_DEBUG is set. + +Ouputs a folder generated_models/ in RAILS_ROOT containing valid Ruby files explaining all the ActiveRecord relationships set up by the plugin, as well as listing the line in the plugin that called each particular association method. + +== Ruby-debug + +Enable by setting HMP_DEBUG to "ruby-debug". + +Starts ruby-debug for the life of the process. + +== Trace + +Enable by setting HMP_DEBUG to "ruby-debug". + +Outputs an indented trace of relevant method calls as they occur. + +== Dependencies + +Enable by setting HMP_DEBUG to "dependencies". + +Turns on Rails' default dependency logging. + +=end + +_logger_warn "debug mode enabled" + +class << ActiveRecord::Base + COLLECTION_METHODS = [:belongs_to, :has_many, :has_and_belongs_to_many, :has_one, + :has_many_polymorphs, :acts_as_double_polymorphic_join].each do |method_name| + alias_method "original_#{method_name}".to_sym, method_name + undef_method method_name + end + + unless defined? GENERATED_CODE_DIR + GENERATED_CODE_DIR = "#{RAILS_ROOT}/generated_models" + + begin + system "rm -rf #{GENERATED_CODE_DIR}" + Dir.mkdir GENERATED_CODE_DIR + rescue Errno::EACCES + _logger_warn "no permissions for generated code dir: #{GENERATED_CODE_DIR}" + end + + if File.exist? GENERATED_CODE_DIR + alias :original_method_missing :method_missing + def method_missing(method_name, *args, &block) + if COLLECTION_METHODS.include? method_name.to_sym + Dir.chdir GENERATED_CODE_DIR do + filename = "#{demodulate(self.name.underscore)}.rb" + contents = File.open(filename).read rescue "\nclass #{self.name}\n\nend\n" + line = caller[1][/\:(\d+)\:/, 1] + contents[-5..-5] = "\n #{method_name} #{args[0..-2].inspect[1..-2]},\n #{args[-1].inspect[1..-2].gsub(" :", "\n :").gsub("=>", " => ")}\n#{ block ? " #{block.inspect.sub(/\@.*\//, '@')}\n" : ""} # called from line #{line}\n\n" + File.open(filename, "w") do |file| + file.puts contents + end + end + # doesn't actually display block contents + self.send("original_#{method_name}", *args, &block) + else + self.send(:original_method_missing, method_name, *args, &block) + end + end + end + + end +end + +case ENV['HMP_DEBUG'] + + when "ruby-debug" + require 'rubygems' + require 'ruby-debug' + Debugger.start + _logger_warn "ruby-debug enabled." + + when "trace" + _logger_warn "method tracing enabled" + $debug_trace_indent = 0 + set_trace_func (proc do |event, file, line, id, binding, classname| + if id.to_s =~ /instantiate/ #/IRB|Wirble|RubyLex|RubyToken|Logger|ConnectionAdapters|SQLite3|MonitorMixin|Benchmark|Inflector|Inflections/ + if event == 'call' + puts (" " * $debug_trace_indent) + "#{event}ed #{classname}\##{id} from #{file.split('/').last}::#{line}" + $debug_trace_indent += 1 + elsif event == 'return' + $debug_trace_indent -= 1 unless $debug_trace_indent == 0 + puts (" " * $debug_trace_indent) + "#{event}ed #{classname}\##{id}" + end + end + end) + + when "dependencies" + _logger_warn "dependency activity being logged" + (::Dependencies.log_activity = true) rescue nil +end diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/dependencies.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/dependencies.rb new file mode 100644 index 0000000..6242d95 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/dependencies.rb @@ -0,0 +1,41 @@ + +=begin rdoc +Adds a minimal dependency injection framework so that owners of polymorphic relationships reload after their children, reinjecting the child helper methods. + +Overrides Dependencies#new_constants_in. +=end + +module Dependencies + + mattr_accessor :injection_graph + self.injection_graph = Hash.new([]) + + # Add a dependency for this target. + def inject_dependency(target, *requirements) + target, requirements = target.to_s, requirements.map(&:to_s) + injection_graph[target] = ((injection_graph[target] + requirements).uniq - [target]) + requirements.each {|requirement| mark_for_unload requirement } + _logger_debug "injection graph: #{injection_graph.inspect}" if Dependencies.log_activity + end + + # Make sure any dependent constants of the constants added by yield are reloaded. + def new_constants_in_with_injection(*descs, &block) # chain + + if Dependencies.log_activity + _logger_debug "autoloaded constants: #{autoloaded_constants.inspect}" + _logger_debug "explicitly unloadable constants: #{explicitly_unloadable_constants.inspect}" + end + + returning(new_constants_in_without_injection(*descs, &block)) do |found| + _logger_debug "new constants: #{found.inspect}" if Dependencies.log_activity and found.any? + found.each do |constant| + injection_graph[constant].each do |requirement| + requirement.constantize + _logger_debug "constantized #{requirement}" if Dependencies.log_activity + end + end + end + end + alias_method_chain :new_constants_in, :injection + +end diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/rake_task_redefine_task.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/rake_task_redefine_task.rb new file mode 100644 index 0000000..99653f8 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/rake_task_redefine_task.rb @@ -0,0 +1,27 @@ + +# Redefine instead of chain a Rake task +# http://www.bigbold.com/snippets/posts/show/2032 + +module Rake + module TaskManager + def redefine_task(task_class, args, &block) + task_name, deps = resolve_args(args) + task_name = task_class.scope_name(@scope, task_name) + deps = [deps] unless deps.respond_to?(:to_ary) + deps = deps.collect {|d| d.to_s } + task = @tasks[task_name.to_s] = task_class.new(task_name, self) + task.application = self + task.add_comment(@last_comment) + @last_comment = nil + task.enhance(deps, &block) + task + end + end + class Task + class << self + def redefine_task(args, &block) + Rake.application.redefine_task(self, args, &block) + end + end + end +end \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/reflection.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/reflection.rb new file mode 100644 index 0000000..3a8d537 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/reflection.rb @@ -0,0 +1,57 @@ +module ActiveRecord #:nodoc: + module Reflection #:nodoc: + + module ClassMethods #:nodoc: + + # Update the default reflection switch so that :has_many_polymorphs types get instantiated. It's not a composed method so we have to override the whole thing. + def create_reflection(macro, name, options, active_record) + case macro + when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many + reflection = AssociationReflection.new(macro, name, options, active_record) + when :composed_of + reflection = AggregateReflection.new(macro, name, options, active_record) + # added by has_many_polymorphs # + when :has_many_polymorphs + reflection = PolymorphicReflection.new(macro, name, options, active_record) + # end added # + end + write_inheritable_hash :reflections, name => reflection + reflection + end + + end + + class PolymorphicError < ActiveRecordError #:nodoc: + end + +=begin rdoc + +The reflection built by the has_many_polymorphs method. + +Inherits from ActiveRecord::Reflection::AssociationReflection. + +=end + + class PolymorphicReflection < AssociationReflection + # Stub out the validity check. Has_many_polymorphs checks validity on macro creation, not on reflection. + def check_validity! + # nothing + end + + # Return the source reflection. + def source_reflection + # normally is the has_many to the through model, but we return ourselves, + # since there isn't a real source class for a polymorphic target + self + end + + # Set the classname of the target. Uses the join class name. + def class_name + # normally is the classname of the association target + @class_name ||= options[:join_class_name] + end + + end + + end +end diff --git a/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/support_methods.rb b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/support_methods.rb new file mode 100644 index 0000000..89ca52a --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/lib/has_many_polymorphs/support_methods.rb @@ -0,0 +1,84 @@ + +class String + + # Changes an underscored string into a class reference. + def _as_class + # classify expects self to be plural + self.classify.constantize + end + + # For compatibility with the Symbol extensions. + alias :_singularize :singularize + alias :_pluralize :pluralize + alias :_classify :classify +end + +class Symbol + + # Changes an underscored symbol into a class reference. + def _as_class; self.to_s._as_class; end + + # Changes a plural symbol into a singular symbol. + def _singularize; self.to_s.singularize.to_sym; end + + # Changes a singular symbol into a plural symbol. + def _pluralize; self.to_s.pluralize.to_sym; end + + # Changes a symbol into a class name string. + def _classify; self.to_s.classify; end +end + +class Array + + # Flattens the first level of self. + def _flatten_once + self.inject([]){|r, el| r + Array(el)} + end + + # Rails 1.2.3 compatibility method. Copied from http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active_support/core_ext/array/extract_options.rb?rev=7217 + def _extract_options! + last.is_a?(::Hash) ? pop : {} + end +end + +class Hash + + # An implementation of select that returns a Hash. + def _select + Hash[*self.select do |key, value| + yield key, value + end._flatten_once] + end +end + +class Object + + # Returns the metaclass of self. + def _metaclass; (class << self; self; end); end + + # Logger shortcut. + def _logger_debug s + s = "** has_many_polymorphs: #{s}" + RAILS_DEFAULT_LOGGER.debug(s) if RAILS_DEFAULT_LOGGER + end + + # Logger shortcut. + def _logger_warn s + s = "** has_many_polymorphs: #{s}" + if RAILS_DEFAULT_LOGGER + RAILS_DEFAULT_LOGGER.warn(s) + else + $stderr.puts(s) + end + end + +end + +class ActiveRecord::Base + + # Return the base class name as a string. + def _base_class_name + self.class.base_class.name.to_s + end + +end diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/bow_wows.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/bow_wows.yml new file mode 100644 index 0000000..00be9d8 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/fixtures/bow_wows.yml @@ -0,0 +1,10 @@ +rover: + id: 1 + name: Rover + created_at: "2007-01-01 12:00:00" + updated_at: "2007-01-04 10:00:00" +spot: + id: 2 + name: Spot + created_at: "2007-01-02 12:00:00" + updated_at: "2007-01-03 10:00:00" diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/cats.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/cats.yml new file mode 100644 index 0000000..aed894f --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/fixtures/cats.yml @@ -0,0 +1,18 @@ +chloe: + id: 1 + cat_type: Kitten + name: Chloe + created_at: "2007-04-01 12:00:00" + updated_at: "2007-04-04 10:00:00" +alice: + id: 2 + cat_type: Kitten + name: Alice + created_at: "2007-04-02 12:00:00" + updated_at: "2007-04-03 10:00:00" +toby: + id: 3 + cat_type: Tabby + name: Toby + created_at: "2007-04-02 12:00:00" + updated_at: "2007-04-03 10:00:00" diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/eaters_foodstuffs.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/eaters_foodstuffs.yml new file mode 100644 index 0000000..e69de29 diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/fish.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/fish.yml new file mode 100644 index 0000000..3974a67 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/fixtures/fish.yml @@ -0,0 +1,12 @@ +swimmy: + id: 1 + name: Swimmy + speed: 10 + created_at: "2007-02-01 12:00:00" + updated_at: "2007-02-04 10:00:00" +jaws: + id: 2 + name: Jaws + speed: 20 + created_at: "2007-02-02 12:00:00" + updated_at: "2007-02-03 10:00:00" diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/frogs.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/frogs.yml new file mode 100644 index 0000000..e9d37d7 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/fixtures/frogs.yml @@ -0,0 +1,5 @@ +froggy: + id: 1 + name: Froggy + created_at: "2007-05-01 12:00:00" + updated_at: "2007-05-04 10:00:00" diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/keep_your_enemies_close.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/keep_your_enemies_close.yml new file mode 100644 index 0000000..e69de29 diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/little_whale_pupils.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/little_whale_pupils.yml new file mode 100644 index 0000000..e69de29 diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/people.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/people.yml new file mode 100644 index 0000000..085d217 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/fixtures/people.yml @@ -0,0 +1,7 @@ +bob: + id: 1 + name: Bob + age: 45 + created_at: "2007-04-01 12:00:00" + updated_at: "2007-04-04 10:00:00" + \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/petfoods.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/petfoods.yml new file mode 100644 index 0000000..a117d29 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/fixtures/petfoods.yml @@ -0,0 +1,11 @@ +kibbles: + the_petfood_primary_key: 1 + name: Kibbles + created_at: "2007-06-01 12:00:00" + updated_at: "2007-06-04 10:00:00" +bits: + the_petfood_primary_key: 2 + name: Bits + created_at: "2007-06-02 12:00:00" + updated_at: "2007-06-03 10:00:00" + \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/whales.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/whales.yml new file mode 100644 index 0000000..bded734 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/fixtures/whales.yml @@ -0,0 +1,5 @@ +shamu: + id: 1 + name: Shamu + created_at: "2007-03-01 12:00:00" + updated_at: "2007-03-04 10:00:00" diff --git a/vendor/plugins/has_many_polymorphs/test/fixtures/wild_boars.yml b/vendor/plugins/has_many_polymorphs/test/fixtures/wild_boars.yml new file mode 100644 index 0000000..73fd3e2 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/fixtures/wild_boars.yml @@ -0,0 +1,10 @@ +puma: + id: 1 + name: Puma + created_at: "2007-07-01 12:00:00" + updated_at: "2007-07-04 10:00:00" +jacrazy: + id: 2 + name: Jacrazy + created_at: "2007-07-02 12:00:00" + updated_at: "2007-07-03 10:00:00" diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/README b/vendor/plugins/has_many_polymorphs/test/integration/app/README new file mode 100644 index 0000000..0d6affd --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/README @@ -0,0 +1,182 @@ +== Welcome to Rails + +Rails is a web-application and persistence framework that includes everything +needed to create database-backed web-applications according to the +Model-View-Control pattern of separation. This pattern splits the view (also +called the presentation) into "dumb" templates that are primarily responsible +for inserting pre-built data in between HTML tags. The model contains the +"smart" domain objects (such as Account, Product, Person, Post) that holds all +the business logic and knows how to persist themselves to a database. The +controller handles the incoming requests (such as Save New Account, Update +Product, Show Post) by manipulating the model and directing data to the view. + +In Rails, the model is handled by what's called an object-relational mapping +layer entitled Active Record. This layer allows you to present the data from +database rows as objects and embellish these data objects with business logic +methods. You can read more about Active Record in +link:files/vendor/rails/activerecord/README.html. + +The controller and view are handled by the Action Pack, which handles both +layers by its two parts: Action View and Action Controller. These two layers +are bundled in a single package due to their heavy interdependence. This is +unlike the relationship between the Active Record and Action Pack that is much +more separate. Each of these packages can be used independently outside of +Rails. You can read more about Action Pack in +link:files/vendor/rails/actionpack/README.html. + + +== Getting started + +1. At the command prompt, start a new rails application using the rails command + and your application name. Ex: rails myapp + (If you've downloaded rails in a complete tgz or zip, this step is already done) +2. Change directory into myapp and start the web server: script/server (run with --help for options) +3. Go to http://localhost:3000/ and get "Welcome aboard: You’re riding the Rails!" +4. Follow the guidelines to start developing your application + + +== Web Servers + +By default, Rails will try to use Mongrel and lighttpd if they are installed, otherwise +Rails will use the WEBrick, the webserver that ships with Ruby. When you run script/server, +Rails will check if Mongrel exists, then lighttpd and finally fall back to WEBrick. This ensures +that you can always get up and running quickly. + +Mongrel is a Ruby-based webserver with a C-component (which requires compilation) that is +suitable for development and deployment of Rails applications. If you have Ruby Gems installed, +getting up and running with mongrel is as easy as: gem install mongrel. +More info at: http://mongrel.rubyforge.org + +If Mongrel is not installed, Rails will look for lighttpd. It's considerably faster than +Mongrel and WEBrick and also suited for production use, but requires additional +installation and currently only works well on OS X/Unix (Windows users are encouraged +to start with Mongrel). We recommend version 1.4.11 and higher. You can download it from +http://www.lighttpd.net. + +And finally, if neither Mongrel or lighttpd are installed, Rails will use the built-in Ruby +web server, WEBrick. WEBrick is a small Ruby web server suitable for development, but not +for production. + +But of course its also possible to run Rails on any platform that supports FCGI. +Apache, LiteSpeed, IIS are just a few. For more information on FCGI, +please visit: http://wiki.rubyonrails.com/rails/pages/FastCGI + + +== Debugging Rails + +Have "tail -f" commands running on the server.log and development.log. Rails will +automatically display debugging and runtime information to these files. Debugging +info will also be shown in the browser on requests from 127.0.0.1. + + +== Breakpoints + +Breakpoint support is available through the script/breakpointer client. This +means that you can break out of execution at any point in the code, investigate +and change the model, AND then resume execution! Example: + + class WeblogController < ActionController::Base + def index + @posts = Post.find(:all) + breakpoint "Breaking out from the list" + end + end + +So the controller will accept the action, run the first line, then present you +with a IRB prompt in the breakpointer window. Here you can do things like: + +Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint' + + >> @posts.inspect + => "[#nil, \"body\"=>nil, \"id\"=>\"1\"}>, + #\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]" + >> @posts.first.title = "hello from a breakpoint" + => "hello from a breakpoint" + +...and even better is that you can examine how your runtime objects actually work: + + >> f = @posts.first + => #nil, "body"=>nil, "id"=>"1"}> + >> f. + Display all 152 possibilities? (y or n) + +Finally, when you're ready to resume execution, you press CTRL-D + + +== Console + +You can interact with the domain model by starting the console through script/console. +Here you'll have all parts of the application configured, just like it is when the +application is running. You can inspect domain models, change values, and save to the +database. Starting the script without arguments will launch it in the development environment. +Passing an argument will specify a different environment, like script/console production. + +To reload your controllers and models after launching the console run reload! + +To reload your controllers and models after launching the console run reload! + + + +== Description of contents + +app + Holds all the code that's specific to this particular application. + +app/controllers + Holds controllers that should be named like weblogs_controller.rb for + automated URL mapping. All controllers should descend from ApplicationController + which itself descends from ActionController::Base. + +app/models + Holds models that should be named like post.rb. + Most models will descend from ActiveRecord::Base. + +app/views + Holds the template files for the view that should be named like + weblogs/index.rhtml for the WeblogsController#index action. All views use eRuby + syntax. + +app/views/layouts + Holds the template files for layouts to be used with views. This models the common + header/footer method of wrapping views. In your views, define a layout using the + layout :default and create a file named default.rhtml. Inside default.rhtml, + call <% yield %> to render the view using this layout. + +app/helpers + Holds view helpers that should be named like weblogs_helper.rb. These are generated + for you automatically when using script/generate for controllers. Helpers can be used to + wrap functionality for your views into methods. + +config + Configuration files for the Rails environment, the routing map, the database, and other dependencies. + +components + Self-contained mini-applications that can bundle together controllers, models, and views. + +db + Contains the database schema in schema.rb. db/migrate contains all + the sequence of Migrations for your schema. + +doc + This directory is where your application documentation will be stored when generated + using rake doc:app + +lib + Application specific libraries. Basically, any kind of custom code that doesn't + belong under controllers, models, or helpers. This directory is in the load path. + +public + The directory available for the web server. Contains subdirectories for images, stylesheets, + and javascripts. Also contains the dispatchers and the default HTML files. This should be + set as the DOCUMENT_ROOT of your web server. + +script + Helper scripts for automation and generation. + +test + Unit and functional tests along with fixtures. When using the script/generate scripts, template + test files will be generated for you and placed in this directory. + +vendor + External libraries that the application depends on. Also includes the plugins subdirectory. + This directory is in the load path. diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/Rakefile b/vendor/plugins/has_many_polymorphs/test/integration/app/Rakefile new file mode 100644 index 0000000..2573c13 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/Rakefile @@ -0,0 +1,19 @@ +# 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' + +namespace :test do + desc "a new rake task to include generators" + Rake::TestTask.new(:generators) do |t| + t.libs << 'lib' + t.test_files = FileList['test/generators/*_test.rb'] + t.verbose = true + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/addresses_controller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/addresses_controller.rb new file mode 100644 index 0000000..6b3c86c --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/addresses_controller.rb @@ -0,0 +1,85 @@ +class AddressesController < ApplicationController + # GET /addresses + # GET /addresses.xml + def index + @addresses = Address.find(:all) + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @addresses } + end + end + + # GET /addresses/1 + # GET /addresses/1.xml + def show + @address = Address.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @address } + end + end + + # GET /addresses/new + # GET /addresses/new.xml + def new + @address = Address.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @address } + end + end + + # GET /addresses/1/edit + def edit + @address = Address.find(params[:id]) + end + + # POST /addresses + # POST /addresses.xml + def create + @address = Address.new(params[:address]) + + respond_to do |format| + if @address.save + flash[:notice] = 'Address was successfully created.' + format.html { redirect_to(@address) } + format.xml { render :xml => @address, :status => :created, :location => @address } + else + format.html { render :action => "new" } + format.xml { render :xml => @address.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /addresses/1 + # PUT /addresses/1.xml + def update + @address = Address.find(params[:id]) + + respond_to do |format| + if @address.update_attributes(params[:address]) + flash[:notice] = 'Address was successfully updated.' + format.html { redirect_to(@address) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @address.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /addresses/1 + # DELETE /addresses/1.xml + def destroy + @address = Address.find(params[:id]) + @address.destroy + + respond_to do |format| + format.html { redirect_to(addresses_url) } + format.xml { head :ok } + end + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/application.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/application.rb new file mode 100644 index 0000000..057f4f7 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/application.rb @@ -0,0 +1,7 @@ +# 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 + # Pick a unique cookie name to distinguish our session data from others' + session :session_key => '_testapp_session_id' +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/sellers_controller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/sellers_controller.rb new file mode 100644 index 0000000..f776aab --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/sellers_controller.rb @@ -0,0 +1,85 @@ +class SellersController < ApplicationController + # GET /sellers + # GET /sellers.xml + def index + @sellers = Seller.find(:all) + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @sellers } + end + end + + # GET /sellers/1 + # GET /sellers/1.xml + def show + @seller = Seller.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @seller } + end + end + + # GET /sellers/new + # GET /sellers/new.xml + def new + @seller = Seller.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @seller } + end + end + + # GET /sellers/1/edit + def edit + @seller = Seller.find(params[:id]) + end + + # POST /sellers + # POST /sellers.xml + def create + @seller = Seller.new(params[:seller]) + + respond_to do |format| + if @seller.save + flash[:notice] = 'Seller was successfully created.' + format.html { redirect_to(@seller) } + format.xml { render :xml => @seller, :status => :created, :location => @seller } + else + format.html { render :action => "new" } + format.xml { render :xml => @seller.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /sellers/1 + # PUT /sellers/1.xml + def update + @seller = Seller.find(params[:id]) + + respond_to do |format| + if @seller.update_attributes(params[:seller]) + flash[:notice] = 'Seller was successfully updated.' + format.html { redirect_to(@seller) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @seller.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /sellers/1 + # DELETE /sellers/1.xml + def destroy + @seller = Seller.find(params[:id]) + @seller.destroy + + respond_to do |format| + format.html { redirect_to(sellers_url) } + format.xml { head :ok } + end + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/states_controller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/states_controller.rb new file mode 100644 index 0000000..54fbcba --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/states_controller.rb @@ -0,0 +1,85 @@ +class StatesController < ApplicationController + # GET /states + # GET /states.xml + def index + @states = State.find(:all) + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @states } + end + end + + # GET /states/1 + # GET /states/1.xml + def show + @state = State.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @state } + end + end + + # GET /states/new + # GET /states/new.xml + def new + @state = State.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @state } + end + end + + # GET /states/1/edit + def edit + @state = State.find(params[:id]) + end + + # POST /states + # POST /states.xml + def create + @state = State.new(params[:state]) + + respond_to do |format| + if @state.save + flash[:notice] = 'State was successfully created.' + format.html { redirect_to(@state) } + format.xml { render :xml => @state, :status => :created, :location => @state } + else + format.html { render :action => "new" } + format.xml { render :xml => @state.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /states/1 + # PUT /states/1.xml + def update + @state = State.find(params[:id]) + + respond_to do |format| + if @state.update_attributes(params[:state]) + flash[:notice] = 'State was successfully updated.' + format.html { redirect_to(@state) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @state.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /states/1 + # DELETE /states/1.xml + def destroy + @state = State.find(params[:id]) + @state.destroy + + respond_to do |format| + format.html { redirect_to(states_url) } + format.xml { head :ok } + end + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/users_controller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/users_controller.rb new file mode 100644 index 0000000..c3ea4e0 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/controllers/users_controller.rb @@ -0,0 +1,85 @@ +class UsersController < ApplicationController + # GET /users + # GET /users.xml + def index + @users = User.find(:all) + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @users } + end + end + + # GET /users/1 + # GET /users/1.xml + def show + @user = User.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @user } + end + end + + # GET /users/new + # GET /users/new.xml + def new + @user = User.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @user } + end + end + + # GET /users/1/edit + def edit + @user = User.find(params[:id]) + end + + # POST /users + # POST /users.xml + def create + @user = User.new(params[:user]) + + respond_to do |format| + if @user.save + flash[:notice] = 'User was successfully created.' + format.html { redirect_to(@user) } + format.xml { render :xml => @user, :status => :created, :location => @user } + else + format.html { render :action => "new" } + format.xml { render :xml => @user.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /users/1 + # PUT /users/1.xml + def update + @user = User.find(params[:id]) + + respond_to do |format| + if @user.update_attributes(params[:user]) + flash[:notice] = 'User was successfully updated.' + format.html { redirect_to(@user) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @user.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /users/1 + # DELETE /users/1.xml + def destroy + @user = User.find(params[:id]) + @user.destroy + + respond_to do |format| + format.html { redirect_to(users_url) } + format.xml { head :ok } + end + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/addresses_helper.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/addresses_helper.rb new file mode 100644 index 0000000..5f4dc13 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/addresses_helper.rb @@ -0,0 +1,2 @@ +module AddressesHelper +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/application_helper.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/application_helper.rb new file mode 100644 index 0000000..22a7940 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/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 diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/sellers_helper.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/sellers_helper.rb new file mode 100644 index 0000000..4bdecd5 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/sellers_helper.rb @@ -0,0 +1,28 @@ +module SellersHelper + + def display_address(seller) + logger.info "Seller Data ====================" + logger.info seller.inspect + logger.info "Seller responds to address " + seller.respond_to?("address").to_s + logger.info "Seller responds to address= " + seller.respond_to?("address=").to_s + # logger.info seller.methods.sort.inspect + logger.info "User Data ====================" + logger.info seller.user.inspect + logger.info "User responds to address " + seller.user.respond_to?("address").to_s + logger.info "User responds to address= " + seller.user.respond_to?("address=").to_s + # logger.info seller.user.methods.sort.inspect + display_address = Array.new + if seller.address + display_address << seller.address.city if seller.address.city + display_address << seller.address.state.abbreviation if seller.address.state && seller.address.state.abbreviation + display_address << seller.address.zip_postal_code if seller.address.zip_postal_code + end + + unless display_address.empty? + "Location: " + display_address.join(", ") + else + "Location: unknown" + end + end + +end \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/states_helper.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/states_helper.rb new file mode 100644 index 0000000..f98bdc7 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/states_helper.rb @@ -0,0 +1,2 @@ +module StatesHelper +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/users_helper.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/users_helper.rb new file mode 100644 index 0000000..2310a24 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/helpers/users_helper.rb @@ -0,0 +1,2 @@ +module UsersHelper +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/address.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/address.rb new file mode 100644 index 0000000..cc040d3 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/address.rb @@ -0,0 +1,4 @@ +class Address < ActiveRecord::Base + belongs_to :user + belongs_to :state +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citation.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citation.rb new file mode 100644 index 0000000..4f5f6d6 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citation.rb @@ -0,0 +1,3 @@ +class Citation < ActiveRecord::Base + has_many_polymorphs :items, :from => [:users, :sellers] +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citations_item.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citations_item.rb new file mode 100644 index 0000000..03525d6 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/citations_item.rb @@ -0,0 +1,4 @@ +class CitationsItem < ActiveRecord::Base + belongs_to :citation + belongs_to :item, :polymorphic => true +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/seller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/seller.rb new file mode 100644 index 0000000..654d23d --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/seller.rb @@ -0,0 +1,4 @@ +class Seller < ActiveRecord::Base + belongs_to :user + delegate :address, :to => :user +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/state.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/state.rb new file mode 100644 index 0000000..8b25cd4 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/state.rb @@ -0,0 +1,3 @@ +class State < ActiveRecord::Base + has_many :addresses +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/user.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/user.rb new file mode 100644 index 0000000..97b8703 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/models/user.rb @@ -0,0 +1,4 @@ +class User < ActiveRecord::Base + has_one :seller + has_one :address +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/edit.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/edit.html.erb new file mode 100644 index 0000000..6b6a389 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/edit.html.erb @@ -0,0 +1,12 @@ +

Editing address

+ +<%= error_messages_for :address %> + +<% form_for(@address) do |f| %> +

+ <%= f.submit "Update" %> +

+<% end %> + +<%= link_to 'Show', @address %> | +<%= link_to 'Back', addresses_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/index.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/index.html.erb new file mode 100644 index 0000000..86d0d38 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/index.html.erb @@ -0,0 +1,18 @@ +

Listing addresses

+ + + + + +<% for address in @addresses %> + + + + + +<% end %> +
<%= link_to 'Show', address %><%= link_to 'Edit', edit_address_path(address) %><%= link_to 'Destroy', address, :confirm => 'Are you sure?', :method => :delete %>
+ +
+ +<%= link_to 'New address', new_address_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/new.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/new.html.erb new file mode 100644 index 0000000..1fae44c --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/new.html.erb @@ -0,0 +1,11 @@ +

New address

+ +<%= error_messages_for :address %> + +<% form_for(@address) do |f| %> +

+ <%= f.submit "Create" %> +

+<% end %> + +<%= link_to 'Back', addresses_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/show.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/show.html.erb new file mode 100644 index 0000000..a75ddbd --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/addresses/show.html.erb @@ -0,0 +1,3 @@ + +<%= link_to 'Edit', edit_address_path(@address) %> | +<%= link_to 'Back', addresses_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/addresses.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/addresses.html.erb new file mode 100644 index 0000000..8458355 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/addresses.html.erb @@ -0,0 +1,17 @@ + + + + + + Addresses: <%= controller.action_name %> + <%= stylesheet_link_tag 'scaffold' %> + + + +

<%= flash[:notice] %>

+ +<%= yield %> + + + diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/sellers.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/sellers.html.erb new file mode 100644 index 0000000..bc08e9b --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/sellers.html.erb @@ -0,0 +1,17 @@ + + + + + + Sellers: <%= controller.action_name %> + <%= stylesheet_link_tag 'scaffold' %> + + + +

<%= flash[:notice] %>

+ +<%= yield %> + + + diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/states.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/states.html.erb new file mode 100644 index 0000000..b2b086f --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/states.html.erb @@ -0,0 +1,17 @@ + + + + + + States: <%= controller.action_name %> + <%= stylesheet_link_tag 'scaffold' %> + + + +

<%= flash[:notice] %>

+ +<%= yield %> + + + diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/users.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/users.html.erb new file mode 100644 index 0000000..23757aa --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/layouts/users.html.erb @@ -0,0 +1,17 @@ + + + + + + Users: <%= controller.action_name %> + <%= stylesheet_link_tag 'scaffold' %> + + + +

<%= flash[:notice] %>

+ +<%= yield %> + + + diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/edit.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/edit.html.erb new file mode 100644 index 0000000..14c4103 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/edit.html.erb @@ -0,0 +1,12 @@ +

Editing seller

+ +<%= error_messages_for :seller %> + +<% form_for(@seller) do |f| %> +

+ <%= f.submit "Update" %> +

+<% end %> + +<%= link_to 'Show', @seller %> | +<%= link_to 'Back', sellers_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/index.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/index.html.erb new file mode 100644 index 0000000..97ef045 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/index.html.erb @@ -0,0 +1,20 @@ +

Listing sellers

+ + + + + +<% for seller in @sellers %> + + + + + + + +<% end %> +
<%= h(seller.company_name) %><%= h(display_address(seller)) %><%= link_to 'Show', seller %><%= link_to 'Edit', edit_seller_path(seller) %><%= link_to 'Destroy', seller, :confirm => 'Are you sure?', :method => :delete %>
+ +
+ +<%= link_to 'New seller', new_seller_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/new.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/new.html.erb new file mode 100644 index 0000000..6814338 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/new.html.erb @@ -0,0 +1,11 @@ +

New seller

+ +<%= error_messages_for :seller %> + +<% form_for(@seller) do |f| %> +

+ <%= f.submit "Create" %> +

+<% end %> + +<%= link_to 'Back', sellers_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/show.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/show.html.erb new file mode 100644 index 0000000..f21dcfa --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/sellers/show.html.erb @@ -0,0 +1,3 @@ + +<%= link_to 'Edit', edit_seller_path(@seller) %> | +<%= link_to 'Back', sellers_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/edit.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/edit.html.erb new file mode 100644 index 0000000..dc59d08 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/edit.html.erb @@ -0,0 +1,12 @@ +

Editing state

+ +<%= error_messages_for :state %> + +<% form_for(@state) do |f| %> +

+ <%= f.submit "Update" %> +

+<% end %> + +<%= link_to 'Show', @state %> | +<%= link_to 'Back', states_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/index.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/index.html.erb new file mode 100644 index 0000000..07c11ae --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/index.html.erb @@ -0,0 +1,19 @@ +

Listing states

+ + + + + +<% for state in @states %> + + + + + + +<% end %> +
<%= state.name %><%= link_to 'Show', state %><%= link_to 'Edit', edit_state_path(state) %><%= link_to 'Destroy', state, :confirm => 'Are you sure?', :method => :delete %>
+ +
+ +<%= link_to 'New state', new_state_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/new.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/new.html.erb new file mode 100644 index 0000000..5caacd5 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/new.html.erb @@ -0,0 +1,11 @@ +

New state

+ +<%= error_messages_for :state %> + +<% form_for(@state) do |f| %> +

+ <%= f.submit "Create" %> +

+<% end %> + +<%= link_to 'Back', states_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/show.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/show.html.erb new file mode 100644 index 0000000..ba5c32f --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/states/show.html.erb @@ -0,0 +1,3 @@ + +<%= link_to 'Edit', edit_state_path(@state) %> | +<%= link_to 'Back', states_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/edit.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/edit.html.erb new file mode 100644 index 0000000..b497ec9 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/edit.html.erb @@ -0,0 +1,12 @@ +

Editing user

+ +<%= error_messages_for :user %> + +<% form_for(@user) do |f| %> +

+ <%= f.submit "Update" %> +

+<% end %> + +<%= link_to 'Show', @user %> | +<%= link_to 'Back', users_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/index.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/index.html.erb new file mode 100644 index 0000000..6397e64 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/index.html.erb @@ -0,0 +1,22 @@ +

Listing users

+ + + + + +<% for user in @users %> + + + + + + + + + +<% end %> +
<%= h(user.login) %><%= h(user.address.line_1) %><%= h(user.address.city) %><%= h(user.address.state.name) %><%= link_to 'Show', user %><%= link_to 'Edit', edit_user_path(user) %><%= link_to 'Destroy', user, :confirm => 'Are you sure?', :method => :delete %>
+ +
+ +<%= link_to 'New user', new_user_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/new.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/new.html.erb new file mode 100644 index 0000000..bc76aa6 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/new.html.erb @@ -0,0 +1,11 @@ +

New user

+ +<%= error_messages_for :user %> + +<% form_for(@user) do |f| %> +

+ <%= f.submit "Create" %> +

+<% end %> + +<%= link_to 'Back', users_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/show.html.erb b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/show.html.erb new file mode 100644 index 0000000..3109a37 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/app/views/users/show.html.erb @@ -0,0 +1,3 @@ + +<%= link_to 'Edit', edit_user_path(@user) %> | +<%= link_to 'Back', users_path %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/boot.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/config/boot.rb new file mode 100644 index 0000000..b7af0c3 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/boot.rb @@ -0,0 +1,45 @@ +# Don't change this file. Configuration is done in config/environment.rb and config/environments/*.rb + +unless defined?(RAILS_ROOT) + root_path = File.join(File.dirname(__FILE__), '..') + + unless RUBY_PLATFORM =~ /(:?mswin|mingw)/ + require 'pathname' + root_path = Pathname.new(root_path).cleanpath(true).to_s + end + + RAILS_ROOT = root_path +end + +unless defined?(Rails::Initializer) + if File.directory?("#{RAILS_ROOT}/vendor/rails") + require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer" + else + require 'rubygems' + + environment_without_comments = IO.readlines(File.dirname(__FILE__) + '/environment.rb').reject { |l| l =~ /^#/ }.join + environment_without_comments =~ /[^#]RAILS_GEM_VERSION = '([\d.]+)'/ + rails_gem_version = $1 + + if version = defined?(RAILS_GEM_VERSION) ? RAILS_GEM_VERSION : rails_gem_version + # Asking for 1.1.6 will give you 1.1.6.5206, if available -- makes it easier to use beta gems + rails_gem = Gem.cache.search('rails', "~>#{version}.0").sort_by { |g| g.version.version }.last + + if rails_gem + gem "rails", "=#{rails_gem.version.version}" + require rails_gem.full_gem_path + '/lib/initializer' + else + STDERR.puts %(Cannot find gem for Rails ~>#{version}.0: + Install the missing gem with 'gem install -v=#{version} rails', or + change environment.rb to define RAILS_GEM_VERSION with your desired version. + ) + exit 1 + end + else + gem "rails" + require 'initializer' + end + end + + Rails::Initializer.run(:set_load_path) +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/database.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/config/database.yml new file mode 100644 index 0000000..76b26dc --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/database.yml @@ -0,0 +1,21 @@ + +development: + adapter: mysql + host: localhost + database: hmp_development + username: root + password: + +test: + adapter: mysql + host: localhost + database: hmp_test + username: root + password: + +production: + adapter: mysql + host: localhost + database: hmp_production + username: root + password: diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/environment.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environment.rb new file mode 100644 index 0000000..0da3703 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environment.rb @@ -0,0 +1,13 @@ + +require File.join(File.dirname(__FILE__), 'boot') + +Rails::Initializer.run do |config| + + if config.action_controller.respond_to? :"session=" + config.action_controller.session = { :session_key => "_myapp_session", :secret => "this is a super secret phrase" } + end + + config.load_paths << "#{RAILS_ROOT}/app/models/person" # moduleless model path +end + +# Dependencies.log_activity = true diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/development.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/development.rb new file mode 100644 index 0000000..a6b7fe2 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/development.rb @@ -0,0 +1,7 @@ +config.cache_classes = false +config.whiny_nils = true +config.action_controller.consider_all_requests_local = true +config.action_controller.perform_caching = false +config.action_view.cache_template_extensions = false +config.action_view.debug_rjs = true +config.action_mailer.raise_delivery_errors = false diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/production.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/production.rb new file mode 100644 index 0000000..cb295b8 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/production.rb @@ -0,0 +1,18 @@ +# 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 + +# 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 diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/test.rb new file mode 100644 index 0000000..f0689b9 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/environments/test.rb @@ -0,0 +1,19 @@ +# 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 + +# Tell ActionMailer 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 \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/locomotive.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/config/locomotive.yml new file mode 100644 index 0000000..01d7977 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/locomotive.yml @@ -0,0 +1,6 @@ +--- +mode: development +runs_at_launch: 0 +identifier: testapp +port: 3005 +bundle: /Applications/Locomotive2/Bundles/rmagickRailsMar2007_i386.locobundle \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/routes.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/config/routes.rb new file mode 100644 index 0000000..b83b6f4 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/routes.rb @@ -0,0 +1,33 @@ +ActionController::Routing::Routes.draw do |map| + map.resources :states + + map.resources :states + + map.resources :addresses + + map.resources :sellers + + map.resources :users + + # The priority is based upon order of creation: first created -> highest priority. + + # Sample of regular route: + # map.connect 'products/:id', :controller => 'catalog', :action => 'view' + # Keep in mind you can assign values other than :controller and :action + + # Sample of named route: + # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' + # This route can be invoked with purchase_url(:id => product.id) + + # You can have the root of your site routed by hooking up '' + # -- just remember to delete public/index.html. + # map.connect '', :controller => "welcome" + + # Allow downloading Web Service WSDL as a file with an extension + # instead of a file named 'wsdl' + map.connect ':controller/service.wsdl', :action => 'wsdl' + + # Install the default route as the lowest priority. + map.connect ':controller/:action/:id.:format' + map.connect ':controller/:action/:id' +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/ultrasphinx/default.base b/vendor/plugins/has_many_polymorphs/test/integration/app/config/ultrasphinx/default.base new file mode 100644 index 0000000..2886ccd --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/ultrasphinx/default.base @@ -0,0 +1,56 @@ +# +# Sphinx/Ultrasphinx user-configurable options. +# +# Copy this file to RAILS_ROOT/config/ultrasphinx. +# You can use individual namespaces if you want (e.g. "development.base"). +# + +indexer +{ + # Indexer running options + mem_limit = 256M +} + +searchd +{ + # Daemon options + # What interface the search daemon should listen on and where to store its logs + address = 0.0.0.0 + port = 3313 + log = /tmp/sphinx/searchd.log + query_log = /tmp/sphinx/query.log + read_timeout = 5 + max_children = 300 + pid_file = /tmp/sphinx/searchd.pid + max_matches = 100000 +} + +client +{ + # Client options + dictionary_name = ts + # How your application connects to the search daemon (not necessarily the same as above) + server_host = localhost + server_port = 3313 +} + +source +{ + # Individual SQL source options + sql_range_step = 20000 + strip_html = 0 + index_html_attrs = + sql_query_post = +} + +index +{ + # Index building options + path = /tmp/sphinx/ + docinfo = extern # just leave this alone + morphology = stem_en + stopwords = # /path/to/stopwords.txt + min_word_len = 1 + charset_type = utf-8 # or sbcs (Single Byte Character Set) + charset_table = 0..9, A..Z->a..z, -, _, ., &, a..z, U+410..U+42F->U+430..U+44F, U+430..U+44F,U+C5->U+E5, U+E5, U+C4->U+E4, U+E4, U+D6->U+F6, U+F6, U+16B, U+0c1->a, U+0c4->a, U+0c9->e, U+0cd->i, U+0d3->o, U+0d4->o, U+0da->u, U+0dd->y, U+0e1->a, U+0e4->a, U+0e9->e, U+0ed->i, U+0f3->o, U+0f4->o, U+0fa->u, U+0fd->y, U+104->U+105, U+105, U+106->U+107, U+10c->c, U+10d->c, U+10e->d, U+10f->d, U+116->U+117, U+117, U+118->U+119, U+11a->e, U+11b->e, U+12E->U+12F, U+12F, U+139->l, U+13a->l, U+13d->l, U+13e->l, U+141->U+142, U+142, U+143->U+144, U+144,U+147->n, U+148->n, U+154->r, U+155->r, U+158->r, U+159->r, U+15A->U+15B, U+15B, U+160->s, U+160->U+161, U+161->s, U+164->t, U+165->t, U+16A->U+16B, U+16B, U+16e->u, U+16f->u, U+172->U+173, U+173, U+179->U+17A, U+17A, U+17B->U+17C, U+17C, U+17d->z, U+17e->z, +} diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/config/ultrasphinx/development.conf.canonical b/vendor/plugins/has_many_polymorphs/test/integration/app/config/ultrasphinx/development.conf.canonical new file mode 100644 index 0000000..f08e8ed --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/config/ultrasphinx/development.conf.canonical @@ -0,0 +1,155 @@ + +# Auto-generated at Wed Oct 03 03:57:12 -0400 2007. +# Hand modifications will be overwritten. +# /Users/eweaver/Desktop/projects/chow/vendor/plugins/ultrasphinx/test/integration/app/config/ultrasphinx/default.base +indexer { + mem_limit = 256M +} +searchd { + read_timeout = 5 + max_children = 300 + log = /tmp/sphinx/searchd.log + port = 3313 + max_matches = 100000 + query_log = /tmp/sphinx/query.log + pid_file = /tmp/sphinx/searchd.pid + address = 0.0.0.0 +} + +# Source configuration + +source geo__states +{ + strip_html = 0 + sql_range_step = 20000 + index_html_attrs = + sql_query_post = + +type = mysql +sql_query_pre = SET SESSION group_concat_max_len = 65535 +sql_query_pre = SET NAMES utf8 + +sql_db = app_development +sql_host = localhost +sql_pass = +sql_user = root +sql_query_range = SELECT MIN(id), MAX(id) FROM states +sql_query = SELECT (states.id * 4 + 0) AS id, CAST(GROUP_CONCAT(addresses.name SEPARATOR ' ') AS CHAR) AS address_name, 0 AS capitalization, 'Geo::State' AS class, 0 AS class_id, '' AS company, '' AS company_name, 0 AS company_name_facet, '' AS content, UNIX_TIMESTAMP('1970-01-01 00:00:00') AS created_at, 0 AS deleted, '' AS email, '__empty_searchable__' AS empty_searchable, '' AS login, '' AS name, '' AS state, 0 AS user_id FROM states LEFT OUTER JOIN addresses ON states.id = addresses.state_id WHERE states.id >= $start AND states.id <= $end GROUP BY id + +sql_group_column = capitalization +sql_group_column = class_id +sql_group_column = company_name_facet +sql_date_column = created_at +sql_group_column = deleted +sql_group_column = user_id +sql_query_info = SELECT * FROM states WHERE states.id = (($id - 0) / 4) +} + + +# Source configuration + +source sellers +{ + strip_html = 0 + sql_range_step = 20000 + index_html_attrs = + sql_query_post = + +type = mysql +sql_query_pre = SET SESSION group_concat_max_len = 65535 +sql_query_pre = SET NAMES utf8 + +sql_db = app_development +sql_host = localhost +sql_pass = +sql_user = root +sql_query_range = SELECT MIN(id), MAX(id) FROM sellers +sql_query = SELECT (sellers.id * 4 + 1) AS id, '' AS address_name, sellers.capitalization AS capitalization, 'Seller' AS class, 1 AS class_id, '' AS company, sellers.company_name AS company_name, CRC32(sellers.company_name) AS company_name_facet, '' AS content, UNIX_TIMESTAMP(sellers.created_at) AS created_at, 0 AS deleted, '' AS email, '__empty_searchable__' AS empty_searchable, '' AS login, '' AS name, '' AS state, sellers.user_id AS user_id FROM sellers WHERE sellers.id >= $start AND sellers.id <= $end GROUP BY id + +sql_group_column = capitalization +sql_group_column = class_id +sql_group_column = company_name_facet +sql_date_column = created_at +sql_group_column = deleted +sql_group_column = user_id +sql_query_info = SELECT * FROM sellers WHERE sellers.id = (($id - 1) / 4) +} + + +# Source configuration + +source geo__addresses +{ + strip_html = 0 + sql_range_step = 20000 + index_html_attrs = + sql_query_post = + +type = mysql +sql_query_pre = SET SESSION group_concat_max_len = 65535 +sql_query_pre = SET NAMES utf8 + +sql_db = app_development +sql_host = localhost +sql_pass = +sql_user = root +sql_query_range = SELECT MIN(id), MAX(id) FROM addresses +sql_query = SELECT (addresses.id * 4 + 2) AS id, '' AS address_name, 0 AS capitalization, 'Geo::Address' AS class, 2 AS class_id, '' AS company, '' AS company_name, 0 AS company_name_facet, CONCAT_WS(' ', addresses.line_1, addresses.line_2, addresses.city, addresses.province_region, addresses.zip_postal_code) AS content, UNIX_TIMESTAMP('1970-01-01 00:00:00') AS created_at, 0 AS deleted, '' AS email, '__empty_searchable__' AS empty_searchable, '' AS login, addresses.name AS name, states.name AS state, 0 AS user_id FROM addresses LEFT OUTER JOIN states ON states.id = addresses.state_id WHERE addresses.id >= $start AND addresses.id <= $end GROUP BY id + +sql_group_column = capitalization +sql_group_column = class_id +sql_group_column = company_name_facet +sql_date_column = created_at +sql_group_column = deleted +sql_group_column = user_id +sql_query_info = SELECT * FROM addresses WHERE addresses.id = (($id - 2) / 4) +} + + +# Source configuration + +source users +{ + strip_html = 0 + sql_range_step = 20000 + index_html_attrs = + sql_query_post = + +type = mysql +sql_query_pre = SET SESSION group_concat_max_len = 65535 +sql_query_pre = SET NAMES utf8 + +sql_db = app_development +sql_host = localhost +sql_pass = +sql_user = root +sql_query_range = SELECT MIN(id), MAX(id) FROM users +sql_query = SELECT (users.id * 4 + 3) AS id, '' AS address_name, 0 AS capitalization, 'User' AS class, 3 AS class_id, sellers.company_name AS company, '' AS company_name, 0 AS company_name_facet, '' AS content, UNIX_TIMESTAMP('1970-01-01 00:00:00') AS created_at, users.deleted AS deleted, users.email AS email, '__empty_searchable__' AS empty_searchable, users.login AS login, '' AS name, '' AS state, 0 AS user_id FROM users LEFT OUTER JOIN sellers ON users.id = sellers.user_id WHERE users.id >= $start AND users.id <= $end AND (deleted = 0) GROUP BY id + +sql_group_column = capitalization +sql_group_column = class_id +sql_group_column = company_name_facet +sql_date_column = created_at +sql_group_column = deleted +sql_group_column = user_id +sql_query_info = SELECT * FROM users WHERE users.id = (($id - 3) / 4) +} + + +# Index configuration + +index complete +{ + source = geo__addresses + source = geo__states + source = sellers + source = users + charset_type = utf-8 + charset_table = 0..9, A..Z->a..z, -, _, ., &, a..z, U+410..U+42F->U+430..U+44F, U+430..U+44F,U+C5->U+E5, U+E5, U+C4->U+E4, U+E4, U+D6->U+F6, U+F6, U+16B, U+0c1->a, U+0c4->a, U+0c9->e, U+0cd->i, U+0d3->o, U+0d4->o, U+0da->u, U+0dd->y, U+0e1->a, U+0e4->a, U+0e9->e, U+0ed->i, U+0f3->o, U+0f4->o, U+0fa->u, U+0fd->y, U+104->U+105, U+105, U+106->U+107, U+10c->c, U+10d->c, U+10e->d, U+10f->d, U+116->U+117, U+117, U+118->U+119, U+11a->e, U+11b->e, U+12E->U+12F, U+12F, U+139->l, U+13a->l, U+13d->l, U+13e->l, U+141->U+142, U+142, U+143->U+144, U+144,U+147->n, U+148->n, U+154->r, U+155->r, U+158->r, U+159->r, U+15A->U+15B, U+15B, U+160->s, U+160->U+161, U+161->s, U+164->t, U+165->t, U+16A->U+16B, U+16B, U+16e->u, U+16f->u, U+172->U+173, U+173, U+179->U+17A, U+17A, U+17B->U+17C, U+17C, U+17d->z, U+17e->z, + min_word_len = 1 + stopwords = + path = /tmp/sphinx//sphinx_index_complete + docinfo = extern + morphology = stem_en +} + diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/001_create_users.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/001_create_users.rb new file mode 100644 index 0000000..de09756 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/001_create_users.rb @@ -0,0 +1,16 @@ +class CreateUsers < ActiveRecord::Migration + def self.up + create_table "users", :force => true do |t| + t.string "login", :limit => 64, :default => "", :null => false + t.string "email", :default => "", :null => false + t.string "crypted_password", :limit => 64, :default => "", :null => false + t.string "salt", :limit => 64, :default => "", :null => false + t.datetime "created_at" + t.datetime "updated_at" + end + end + + def self.down + drop_table :users + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/002_create_sellers.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/002_create_sellers.rb new file mode 100644 index 0000000..ecb077f --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/002_create_sellers.rb @@ -0,0 +1,14 @@ +class CreateSellers < ActiveRecord::Migration + def self.up + create_table "sellers", :force => true do |t| + t.integer "user_id", :null => false + t.string "company_name" + t.datetime "created_at" + t.datetime "updated_at" + end + end + + def self.down + drop_table :sellers + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/003_create_addresses.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/003_create_addresses.rb new file mode 100644 index 0000000..a54f224 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/003_create_addresses.rb @@ -0,0 +1,19 @@ +class CreateAddresses < ActiveRecord::Migration + def self.up + create_table "addresses", :force => true do |t| + t.integer "user_id", :null => false + t.string "name" + t.string "line_1", :default => "", :null => false + t.string "line_2" + t.string "city", :default => "", :null => false + t.integer "state_id", :null => false + t.string "province_region" + t.string "zip_postal_code" + t.integer "country_id", :null => false + end + end + + def self.down + drop_table :addresses + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/004_create_states.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/004_create_states.rb new file mode 100644 index 0000000..797e6f7 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/004_create_states.rb @@ -0,0 +1,12 @@ +class CreateStates < ActiveRecord::Migration + def self.up + create_table "states", :force => true do |t| + t.string "name", :default => "", :null => false + t.string "abbreviation", :default => "", :null => false + end + end + + def self.down + drop_table "states" + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/005_add_capitalization_to_seller.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/005_add_capitalization_to_seller.rb new file mode 100644 index 0000000..4042173 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/005_add_capitalization_to_seller.rb @@ -0,0 +1,9 @@ +class AddCapitalizationToSeller < ActiveRecord::Migration + def self.up + add_column :sellers, :capitalization, :float, :default => 0.0 + end + + def self.down + remove_column :sellers, :capitalization + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/006_add_deleted_to_user.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/006_add_deleted_to_user.rb new file mode 100644 index 0000000..2690b86 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/006_add_deleted_to_user.rb @@ -0,0 +1,9 @@ +class AddDeletedToUser < ActiveRecord::Migration + def self.up + add_column :users, :deleted, :boolean, :default => false + end + + def self.down + remove_column :users, :deleted + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/007_add_lat_and_long_to_address.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/007_add_lat_and_long_to_address.rb new file mode 100644 index 0000000..83ad382 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/007_add_lat_and_long_to_address.rb @@ -0,0 +1,11 @@ +class AddLatAndLongToAddress < ActiveRecord::Migration + def self.up + add_column :addresses, :lat, :float + add_column :addresses, :long, :float + end + + def self.down + remove_column :addresses, :lat + remove_column :addresses, :long + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/008_create_citations.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/008_create_citations.rb new file mode 100644 index 0000000..be9190e --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/008_create_citations.rb @@ -0,0 +1,12 @@ +class CreateCitations < ActiveRecord::Migration + def self.up + create_table :citations do |t| + t.string :name + t.timestamps + end + end + + def self.down + drop_table :citations + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/009_create_citations_items.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/009_create_citations_items.rb new file mode 100644 index 0000000..1aafd73 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/db/migrate/009_create_citations_items.rb @@ -0,0 +1,14 @@ +class CreateCitationsItems < ActiveRecord::Migration + def self.up + create_table :citations_items do |t| + t.integer :citation_id, :null => false + t.integer :item_id, :null => false + t.string :item_type, :null => false + t.timestamps + end + end + + def self.down + drop_table :citations_items + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/doc/README_FOR_APP b/vendor/plugins/has_many_polymorphs/test/integration/app/doc/README_FOR_APP new file mode 100644 index 0000000..ac6c149 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/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 appdoc" to generate API documentation for your models and controllers. \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/generators/commenting_generator_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/generators/commenting_generator_test.rb new file mode 100644 index 0000000..96c6a79 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/generators/commenting_generator_test.rb @@ -0,0 +1,83 @@ +require File.dirname(__FILE__) + '/../test_helper' +require 'fileutils' + +class CommentingGeneratorTest < Test::Unit::TestCase + + def test_ensure_comments_dont_exist + # make sure the comments are already defined + assert_equal false, Object.send(:const_defined?, :Comment) + assert_equal false, Object.send(:const_defined?, :Commenting) + end + + def test_ensure_files_exist_after_generator_runs + run_generator + + # make sure the files are there + for generated_file in generated_files do + assert File.exists?(File.expand_path(generated_file)) + end + end + + def test_classes_exist_with_associations + run_generator + assert_nothing_raised { Commenting } + assert_nothing_raised { Comment } + citation = Citation.find(:first) + assert !citation.nil? + assert citation.respond_to?(:comments) + user = User.find(:first) + assert !user.nil? + assert user.respond_to?(:comments) + end + + def teardown + Object.send(:remove_const, :Comment) if Object.send(:const_defined?, :Comment) + Object.send(:remove_const, :Commenting) if Object.send(:const_defined?, :Commenting) + remove_all_generated_files + remove_require_for_commenting_extensions + end + + def generated_files + generated_files = [File.join(File.dirname(__FILE__), '..', '..', 'app', 'models', 'comment.rb')] + generated_files << File.join(File.dirname(__FILE__), '..', '..', 'app', 'models', 'commenting.rb') + generated_files << File.join(File.dirname(__FILE__), '..', '..', 'test', 'unit', 'commenting_test.rb') + generated_files << File.join(File.dirname(__FILE__), '..', '..', 'test', 'unit', 'comment_test.rb') + generated_files << File.join(File.dirname(__FILE__), '..', '..', 'lib', 'commenting_extensions.rb') + generated_files << File.join(File.dirname(__FILE__), '..', '..', 'test', 'fixtures', 'comments.yml') + generated_files << File.join(File.dirname(__FILE__), '..', '..', 'test', 'fixtures', 'commentings.yml') + end + + def remove_all_generated_files + for generated_file in generated_files do + if File.exists?(generated_file) + assert FileUtils.rm(generated_file) + end + end + end + + def run_migrate + `rake db:migrate RAILS_ENV=test` + end + + def run_generator + command = File.join(File.dirname(__FILE__), '..', '..', 'script', 'generate') + `#{command} commenting Citation User` + run_migrate + end + + def remove_require_for_commenting_extensions + environment = File.join(File.dirname(__FILE__), '..', '..', 'config', 'environment.rb') + new_environment = '' + if File.exists?(environment) + if (open(environment) { |file| file.grep(/Rails/).any? }) + IO.readlines(environment).each do |line| + new_environment += line unless line.match(/commenting_extensions/i) + end + File.open(environment, "w+") do |f| + f.pos = 0 + f.print new_environment + end + end + end + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/404.html b/vendor/plugins/has_many_polymorphs/test/integration/app/public/404.html new file mode 100644 index 0000000..eff660b --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/404.html @@ -0,0 +1,30 @@ + + + + + + + The page you were looking for doesn't exist (404) + + + + + +
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+ + \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/500.html b/vendor/plugins/has_many_polymorphs/test/integration/app/public/500.html new file mode 100644 index 0000000..f0aee0e --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/500.html @@ -0,0 +1,30 @@ + + + + + + + We're sorry, but something went wrong + + + + + +
+

We're sorry, but something went wrong.

+

We've been notified about this issue and we'll take a look at it shortly.

+
+ + \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/dispatch.cgi b/vendor/plugins/has_many_polymorphs/test/integration/app/public/dispatch.cgi new file mode 100755 index 0000000..9b5ae76 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/dispatch.cgi @@ -0,0 +1,10 @@ +#!/usr/local/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 \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/dispatch.fcgi b/vendor/plugins/has_many_polymorphs/test/integration/app/public/dispatch.fcgi new file mode 100755 index 0000000..664dbbb --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/dispatch.fcgi @@ -0,0 +1,24 @@ +#!/usr/bin/env 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! diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/dispatch.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/public/dispatch.rb new file mode 100755 index 0000000..9b5ae76 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/dispatch.rb @@ -0,0 +1,10 @@ +#!/usr/local/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 \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/favicon.ico b/vendor/plugins/has_many_polymorphs/test/integration/app/public/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/images/rails.png b/vendor/plugins/has_many_polymorphs/test/integration/app/public/images/rails.png new file mode 100644 index 0000000..b8441f1 Binary files /dev/null and b/vendor/plugins/has_many_polymorphs/test/integration/app/public/images/rails.png differ diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/index.html b/vendor/plugins/has_many_polymorphs/test/integration/app/public/index.html new file mode 100644 index 0000000..a2daab7 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/index.html @@ -0,0 +1,277 @@ + + + + + Ruby on Rails: Welcome aboard + + + + + + +
+ + +
+ + + + +
+

Getting started

+

Here’s how to get rolling:

+ +
    +
  1. +

    Create your databases and edit config/database.yml

    +

    Rails needs to know your login and password.

    +
  2. + +
  3. +

    Use script/generate to create your models and controllers

    +

    To see all available options, run it without parameters.

    +
  4. + +
  5. +

    Set up a default route and remove or rename this file

    +

    Routes are setup in config/routes.rb.

    +
  6. +
+
+
+ + +
+ + \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/application.js b/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/application.js new file mode 100644 index 0000000..fe45776 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/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 diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/controls.js b/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/controls.js new file mode 100644 index 0000000..8c273f8 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/controls.js @@ -0,0 +1,833 @@ +// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// (c) 2005, 2006 Ivan Krstic (http://blogs.law.harvard.edu/ivan) +// (c) 2005, 2006 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 = function() {}; +Autocompleter.Base.prototype = { + baseInitialize: function(element, update, options) { + this.element = $(element); + this.update = $(update); + this.hasFocus = false; + this.changed = false; + this.active = false; + this.index = 0; + this.entryCount = 0; + + 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); + + 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, "keypress", this.onKeyPress.bindAsEventListener(this)); + }, + + show: function() { + if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update); + if(!this.iefix && + (navigator.appVersion.indexOf('MSIE')>0) && + (navigator.userAgent.indexOf('Opera')<0) && + (Element.getStyle(this.update, 'position')=='absolute')) { + new Insertion.After(this.update, + ''); + 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(); + if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event); + return; + case Event.KEY_DOWN: + this.markNext(); + this.render(); + if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event); + return; + } + else + if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || + (navigator.appVersion.indexOf('AppleWebKit') > 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 = document.getElementsByClassName(this.options.select, selectedElement) || []; + if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select); + } else + value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal'); + + var lastTokenPos = this.findLastToken(); + if (lastTokenPos != -1) { + var newValue = this.element.value.substr(0, lastTokenPos + 1); + var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/); + if (whitespace) + newValue += whitespace[0]; + this.element.value = newValue + value; + } else { + this.element.value = 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; + if(this.getToken().length>=this.options.minChars) { + this.startIndicator(); + this.getUpdatedChoices(); + } else { + this.active = false; + this.hide(); + } + }, + + getToken: function() { + var tokenPos = this.findLastToken(); + if (tokenPos != -1) + var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,''); + else + var ret = this.element.value; + + return /\n/.test(ret) ? '' : ret; + }, + + findLastToken: function() { + var lastTokenPos = -1; + + for (var i=0; i lastTokenPos) + lastTokenPos = thisTokenPos; + } + return lastTokenPos; + } +} + +Ajax.Autocompleter = Class.create(); +Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), { + 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() { + 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.Local.prototype = Object.extend(new 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("
  • " + elem.substr(0, entry.length) + "" + + elem.substr(entry.length) + "
  • "); + 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("
  • " + elem.substr(0, foundPos) + "" + + elem.substr(foundPos, entry.length) + "" + elem.substr( + foundPos + entry.length) + "
  • "); + 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 "
      " + ret.join('') + "
    "; + } + }, options || {}); + } +}); + +// AJAX in-place editor +// +// see documentation on http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor + +// 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(); +Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99"; +Ajax.InPlaceEditor.prototype = { + initialize: function(element, url, options) { + this.url = url; + this.element = $(element); + + this.options = Object.extend({ + paramName: "value", + okButton: true, + okText: "ok", + cancelLink: true, + cancelText: "cancel", + savingText: "Saving...", + clickToEditText: "Click to edit", + okText: "ok", + rows: 1, + onComplete: function(transport, element) { + new Effect.Highlight(element, {startcolor: this.options.highlightcolor}); + }, + onFailure: function(transport) { + alert("Error communicating with the server: " + transport.responseText.stripTags()); + }, + callback: function(form) { + return Form.serialize(form); + }, + handleLineBreaks: true, + loadingText: 'Loading...', + savingClassName: 'inplaceeditor-saving', + loadingClassName: 'inplaceeditor-loading', + formClassName: 'inplaceeditor-form', + highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor, + highlightendcolor: "#FFFFFF", + externalControl: null, + submitOnBlur: false, + ajaxOptions: {}, + evalScripts: false + }, options || {}); + + if(!this.options.formId && this.element.id) { + this.options.formId = this.element.id + "-inplaceeditor"; + if ($(this.options.formId)) { + // there's already a form with that name, don't specify an id + this.options.formId = null; + } + } + + if (this.options.externalControl) { + this.options.externalControl = $(this.options.externalControl); + } + + this.originalBackground = Element.getStyle(this.element, 'background-color'); + if (!this.originalBackground) { + this.originalBackground = "transparent"; + } + + this.element.title = this.options.clickToEditText; + + this.onclickListener = this.enterEditMode.bindAsEventListener(this); + this.mouseoverListener = this.enterHover.bindAsEventListener(this); + this.mouseoutListener = this.leaveHover.bindAsEventListener(this); + Event.observe(this.element, 'click', this.onclickListener); + Event.observe(this.element, 'mouseover', this.mouseoverListener); + Event.observe(this.element, 'mouseout', this.mouseoutListener); + if (this.options.externalControl) { + Event.observe(this.options.externalControl, 'click', this.onclickListener); + Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener); + Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener); + } + }, + enterEditMode: function(evt) { + if (this.saving) return; + if (this.editing) return; + this.editing = true; + this.onEnterEditMode(); + if (this.options.externalControl) { + Element.hide(this.options.externalControl); + } + Element.hide(this.element); + this.createForm(); + this.element.parentNode.insertBefore(this.form, this.element); + if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField); + // stop the event to avoid a page refresh in Safari + if (evt) { + Event.stop(evt); + } + return false; + }, + createForm: function() { + this.form = document.createElement("form"); + this.form.id = this.options.formId; + Element.addClassName(this.form, this.options.formClassName) + this.form.onsubmit = this.onSubmit.bind(this); + + this.createEditField(); + + if (this.options.textarea) { + var br = document.createElement("br"); + this.form.appendChild(br); + } + + if (this.options.okButton) { + okButton = document.createElement("input"); + okButton.type = "submit"; + okButton.value = this.options.okText; + okButton.className = 'editor_ok_button'; + this.form.appendChild(okButton); + } + + if (this.options.cancelLink) { + cancelLink = document.createElement("a"); + cancelLink.href = "#"; + cancelLink.appendChild(document.createTextNode(this.options.cancelText)); + cancelLink.onclick = this.onclickCancel.bind(this); + cancelLink.className = 'editor_cancel'; + this.form.appendChild(cancelLink); + } + }, + hasHTMLLineBreaks: function(string) { + if (!this.options.handleLineBreaks) return false; + return string.match(/
    /i); + }, + convertHTMLLineBreaks: function(string) { + return string.replace(/
    /gi, "\n").replace(//gi, "\n").replace(/<\/p>/gi, "\n").replace(/

    /gi, ""); + }, + createEditField: function() { + var text; + if(this.options.loadTextURL) { + text = this.options.loadingText; + } else { + text = this.getText(); + } + + var obj = this; + + if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) { + this.options.textarea = false; + var textField = document.createElement("input"); + textField.obj = this; + textField.type = "text"; + textField.name = this.options.paramName; + textField.value = text; + textField.style.backgroundColor = this.options.highlightcolor; + textField.className = 'editor_field'; + var size = this.options.size || this.options.cols || 0; + if (size != 0) textField.size = size; + if (this.options.submitOnBlur) + textField.onblur = this.onSubmit.bind(this); + this.editField = textField; + } else { + this.options.textarea = true; + var textArea = document.createElement("textarea"); + textArea.obj = this; + textArea.name = this.options.paramName; + textArea.value = this.convertHTMLLineBreaks(text); + textArea.rows = this.options.rows; + textArea.cols = this.options.cols || 40; + textArea.className = 'editor_field'; + if (this.options.submitOnBlur) + textArea.onblur = this.onSubmit.bind(this); + this.editField = textArea; + } + + if(this.options.loadTextURL) { + this.loadExternalText(); + } + this.form.appendChild(this.editField); + }, + getText: function() { + return this.element.innerHTML; + }, + loadExternalText: function() { + Element.addClassName(this.form, this.options.loadingClassName); + this.editField.disabled = true; + new Ajax.Request( + this.options.loadTextURL, + Object.extend({ + asynchronous: true, + onComplete: this.onLoadedExternalText.bind(this) + }, this.options.ajaxOptions) + ); + }, + onLoadedExternalText: function(transport) { + Element.removeClassName(this.form, this.options.loadingClassName); + this.editField.disabled = false; + this.editField.value = transport.responseText.stripTags(); + Field.scrollFreeActivate(this.editField); + }, + onclickCancel: function() { + this.onComplete(); + this.leaveEditMode(); + return false; + }, + onFailure: function(transport) { + this.options.onFailure(transport); + if (this.oldInnerHTML) { + this.element.innerHTML = this.oldInnerHTML; + this.oldInnerHTML = null; + } + return false; + }, + onSubmit: function() { + // onLoading resets these so we need to save them away for the Ajax call + var form = this.form; + var value = this.editField.value; + + // do this first, sometimes the ajax call returns before we get a chance to switch on Saving... + // which means this will actually switch on Saving... *after* we've left edit mode causing Saving... + // to be displayed indefinitely + this.onLoading(); + + if (this.options.evalScripts) { + new Ajax.Request( + this.url, Object.extend({ + parameters: this.options.callback(form, value), + onComplete: this.onComplete.bind(this), + onFailure: this.onFailure.bind(this), + asynchronous:true, + evalScripts:true + }, this.options.ajaxOptions)); + } else { + new Ajax.Updater( + { success: this.element, + // don't update on failure (this could be an option) + failure: null }, + this.url, Object.extend({ + parameters: this.options.callback(form, value), + onComplete: this.onComplete.bind(this), + onFailure: this.onFailure.bind(this) + }, this.options.ajaxOptions)); + } + // stop the event to avoid a page refresh in Safari + if (arguments.length > 1) { + Event.stop(arguments[0]); + } + return false; + }, + onLoading: function() { + this.saving = true; + this.removeForm(); + this.leaveHover(); + this.showSaving(); + }, + showSaving: function() { + this.oldInnerHTML = this.element.innerHTML; + this.element.innerHTML = this.options.savingText; + Element.addClassName(this.element, this.options.savingClassName); + this.element.style.backgroundColor = this.originalBackground; + Element.show(this.element); + }, + removeForm: function() { + if(this.form) { + if (this.form.parentNode) Element.remove(this.form); + this.form = null; + } + }, + enterHover: function() { + if (this.saving) return; + this.element.style.backgroundColor = this.options.highlightcolor; + if (this.effect) { + this.effect.cancel(); + } + Element.addClassName(this.element, this.options.hoverClassName) + }, + leaveHover: function() { + if (this.options.backgroundColor) { + this.element.style.backgroundColor = this.oldBackground; + } + Element.removeClassName(this.element, this.options.hoverClassName) + if (this.saving) return; + this.effect = new Effect.Highlight(this.element, { + startcolor: this.options.highlightcolor, + endcolor: this.options.highlightendcolor, + restorecolor: this.originalBackground + }); + }, + leaveEditMode: function() { + Element.removeClassName(this.element, this.options.savingClassName); + this.removeForm(); + this.leaveHover(); + this.element.style.backgroundColor = this.originalBackground; + Element.show(this.element); + if (this.options.externalControl) { + Element.show(this.options.externalControl); + } + this.editing = false; + this.saving = false; + this.oldInnerHTML = null; + this.onLeaveEditMode(); + }, + onComplete: function(transport) { + this.leaveEditMode(); + this.options.onComplete.bind(this)(transport, this.element); + }, + onEnterEditMode: function() {}, + onLeaveEditMode: function() {}, + dispose: function() { + if (this.oldInnerHTML) { + this.element.innerHTML = this.oldInnerHTML; + } + this.leaveEditMode(); + Event.stopObserving(this.element, 'click', this.onclickListener); + Event.stopObserving(this.element, 'mouseover', this.mouseoverListener); + Event.stopObserving(this.element, 'mouseout', this.mouseoutListener); + if (this.options.externalControl) { + Event.stopObserving(this.options.externalControl, 'click', this.onclickListener); + Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener); + Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener); + } + } +}; + +Ajax.InPlaceCollectionEditor = Class.create(); +Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype); +Object.extend(Ajax.InPlaceCollectionEditor.prototype, { + createEditField: function() { + if (!this.cached_selectTag) { + var selectTag = document.createElement("select"); + var collection = this.options.collection || []; + var optionTag; + collection.each(function(e,i) { + optionTag = document.createElement("option"); + optionTag.value = (e instanceof Array) ? e[0] : e; + if((typeof this.options.value == 'undefined') && + ((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true; + if(this.options.value==optionTag.value) optionTag.selected = true; + optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e)); + selectTag.appendChild(optionTag); + }.bind(this)); + this.cached_selectTag = selectTag; + } + + this.editField = this.cached_selectTag; + if(this.options.loadTextURL) this.loadExternalText(); + this.form.appendChild(this.editField); + this.options.callback = function(form, value) { + return "value=" + encodeURIComponent(value); + } + } +}); + +// Delayed observer, like Form.Element.Observer, +// but waits for delay after last key input +// Ideal for live-search fields + +Form.Element.DelayedObserver = Class.create(); +Form.Element.DelayedObserver.prototype = { + initialize: function(element, delay, callback) { + this.delay = delay || 0.5; + this.element = $(element); + this.callback = callback; + this.timer = null; + this.lastValue = $F(this.element); + Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this)); + }, + delayedListener: function(event) { + if(this.lastValue == $F(this.element)) return; + if(this.timer) clearTimeout(this.timer); + this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000); + this.lastValue = $F(this.element); + }, + onTimerEvent: function() { + this.timer = null; + this.callback(this.element, $F(this.element)); + } +}; diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/dragdrop.js b/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/dragdrop.js new file mode 100644 index 0000000..c71ddb8 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/dragdrop.js @@ -0,0 +1,942 @@ +// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// (c) 2005, 2006 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz) +// +// 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/ + +if(typeof Effect == 'undefined') + throw("dragdrop.js requires including script.aculo.us' effects.js library"); + +var Droppables = { + drops: [], + + remove: function(element) { + this.drops = this.drops.reject(function(d) { return d.element==$(element) }); + }, + + add: function(element) { + element = $(element); + var options = Object.extend({ + greedy: true, + hoverclass: null, + tree: false + }, arguments[1] || {}); + + // cache containers + if(options.containment) { + options._containers = []; + var containment = options.containment; + if((typeof containment == 'object') && + (containment.constructor == Array)) { + containment.each( function(c) { options._containers.push($(c)) }); + } else { + options._containers.push($(containment)); + } + } + + if(options.accept) options.accept = [options.accept].flatten(); + + Element.makePositioned(element); // fix IE + options.element = element; + + this.drops.push(options); + }, + + findDeepestChild: function(drops) { + deepest = drops[0]; + + for (i = 1; i < drops.length; ++i) + if (Element.isParent(drops[i].element, deepest.element)) + deepest = drops[i]; + + return deepest; + }, + + isContained: function(element, drop) { + var containmentNode; + if(drop.tree) { + containmentNode = element.treeNode; + } else { + containmentNode = element.parentNode; + } + return drop._containers.detect(function(c) { return containmentNode == c }); + }, + + isAffected: function(point, element, drop) { + return ( + (drop.element!=element) && + ((!drop._containers) || + this.isContained(element, drop)) && + ((!drop.accept) || + (Element.classNames(element).detect( + function(v) { return drop.accept.include(v) } ) )) && + Position.within(drop.element, point[0], point[1]) ); + }, + + deactivate: function(drop) { + if(drop.hoverclass) + Element.removeClassName(drop.element, drop.hoverclass); + this.last_active = null; + }, + + activate: function(drop) { + if(drop.hoverclass) + Element.addClassName(drop.element, drop.hoverclass); + this.last_active = drop; + }, + + show: function(point, element) { + if(!this.drops.length) return; + var affected = []; + + if(this.last_active) this.deactivate(this.last_active); + this.drops.each( function(drop) { + if(Droppables.isAffected(point, element, drop)) + affected.push(drop); + }); + + if(affected.length>0) { + drop = Droppables.findDeepestChild(affected); + Position.within(drop.element, point[0], point[1]); + if(drop.onHover) + drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); + + Droppables.activate(drop); + } + }, + + fire: function(event, element) { + if(!this.last_active) return; + Position.prepare(); + + if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) + if (this.last_active.onDrop) + this.last_active.onDrop(element, this.last_active.element, event); + }, + + reset: function() { + if(this.last_active) + this.deactivate(this.last_active); + } +} + +var Draggables = { + drags: [], + observers: [], + + register: function(draggable) { + if(this.drags.length == 0) { + this.eventMouseUp = this.endDrag.bindAsEventListener(this); + this.eventMouseMove = this.updateDrag.bindAsEventListener(this); + this.eventKeypress = this.keyPress.bindAsEventListener(this); + + Event.observe(document, "mouseup", this.eventMouseUp); + Event.observe(document, "mousemove", this.eventMouseMove); + Event.observe(document, "keypress", this.eventKeypress); + } + this.drags.push(draggable); + }, + + unregister: function(draggable) { + this.drags = this.drags.reject(function(d) { return d==draggable }); + if(this.drags.length == 0) { + Event.stopObserving(document, "mouseup", this.eventMouseUp); + Event.stopObserving(document, "mousemove", this.eventMouseMove); + Event.stopObserving(document, "keypress", this.eventKeypress); + } + }, + + activate: function(draggable) { + if(draggable.options.delay) { + this._timeout = setTimeout(function() { + Draggables._timeout = null; + window.focus(); + Draggables.activeDraggable = draggable; + }.bind(this), draggable.options.delay); + } else { + window.focus(); // allows keypress events if window isn't currently focused, fails for Safari + this.activeDraggable = draggable; + } + }, + + deactivate: function() { + this.activeDraggable = null; + }, + + updateDrag: function(event) { + if(!this.activeDraggable) return; + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + // Mozilla-based browsers fire successive mousemove events with + // the same coordinates, prevent needless redrawing (moz bug?) + if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return; + this._lastPointer = pointer; + + this.activeDraggable.updateDrag(event, pointer); + }, + + endDrag: function(event) { + if(this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + } + if(!this.activeDraggable) return; + this._lastPointer = null; + this.activeDraggable.endDrag(event); + this.activeDraggable = null; + }, + + keyPress: function(event) { + if(this.activeDraggable) + this.activeDraggable.keyPress(event); + }, + + addObserver: function(observer) { + this.observers.push(observer); + this._cacheObserverCallbacks(); + }, + + removeObserver: function(element) { // element instead of observer fixes mem leaks + this.observers = this.observers.reject( function(o) { return o.element==element }); + this._cacheObserverCallbacks(); + }, + + notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' + if(this[eventName+'Count'] > 0) + this.observers.each( function(o) { + if(o[eventName]) o[eventName](eventName, draggable, event); + }); + if(draggable.options[eventName]) draggable.options[eventName](draggable, event); + }, + + _cacheObserverCallbacks: function() { + ['onStart','onEnd','onDrag'].each( function(eventName) { + Draggables[eventName+'Count'] = Draggables.observers.select( + function(o) { return o[eventName]; } + ).length; + }); + } +} + +/*--------------------------------------------------------------------------*/ + +var Draggable = Class.create(); +Draggable._dragging = {}; + +Draggable.prototype = { + initialize: function(element) { + var defaults = { + handle: false, + reverteffect: function(element, top_offset, left_offset) { + var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02; + new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur, + queue: {scope:'_draggable', position:'end'} + }); + }, + endeffect: function(element) { + var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0; + new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, + queue: {scope:'_draggable', position:'end'}, + afterFinish: function(){ + Draggable._dragging[element] = false + } + }); + }, + zindex: 1000, + revert: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] } + delay: 0 + }; + + if(!arguments[1] || typeof arguments[1].endeffect == 'undefined') + Object.extend(defaults, { + starteffect: function(element) { + element._opacity = Element.getOpacity(element); + Draggable._dragging[element] = true; + new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); + } + }); + + var options = Object.extend(defaults, arguments[1] || {}); + + this.element = $(element); + + if(options.handle && (typeof options.handle == 'string')) + this.handle = this.element.down('.'+options.handle, 0); + + if(!this.handle) this.handle = $(options.handle); + if(!this.handle) this.handle = this.element; + + if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) { + options.scroll = $(options.scroll); + this._isScrollChild = Element.childOf(this.element, options.scroll); + } + + Element.makePositioned(this.element); // fix IE + + this.delta = this.currentDelta(); + this.options = options; + this.dragging = false; + + this.eventMouseDown = this.initDrag.bindAsEventListener(this); + Event.observe(this.handle, "mousedown", this.eventMouseDown); + + Draggables.register(this); + }, + + destroy: function() { + Event.stopObserving(this.handle, "mousedown", this.eventMouseDown); + Draggables.unregister(this); + }, + + currentDelta: function() { + return([ + parseInt(Element.getStyle(this.element,'left') || '0'), + parseInt(Element.getStyle(this.element,'top') || '0')]); + }, + + initDrag: function(event) { + if(typeof Draggable._dragging[this.element] != 'undefined' && + Draggable._dragging[this.element]) return; + if(Event.isLeftClick(event)) { + // abort on form elements, fixes a Firefox issue + var src = Event.element(event); + if(src.tagName && ( + src.tagName=='INPUT' || + src.tagName=='SELECT' || + src.tagName=='OPTION' || + src.tagName=='BUTTON' || + src.tagName=='TEXTAREA')) return; + + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + var pos = Position.cumulativeOffset(this.element); + this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) }); + + Draggables.activate(this); + Event.stop(event); + } + }, + + startDrag: function(event) { + this.dragging = true; + + if(this.options.zindex) { + this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); + this.element.style.zIndex = this.options.zindex; + } + + if(this.options.ghosting) { + this._clone = this.element.cloneNode(true); + Position.absolutize(this.element); + this.element.parentNode.insertBefore(this._clone, this.element); + } + + if(this.options.scroll) { + if (this.options.scroll == window) { + var where = this._getWindowScroll(this.options.scroll); + this.originalScrollLeft = where.left; + this.originalScrollTop = where.top; + } else { + this.originalScrollLeft = this.options.scroll.scrollLeft; + this.originalScrollTop = this.options.scroll.scrollTop; + } + } + + Draggables.notify('onStart', this, event); + + if(this.options.starteffect) this.options.starteffect(this.element); + }, + + updateDrag: function(event, pointer) { + if(!this.dragging) this.startDrag(event); + Position.prepare(); + Droppables.show(pointer, this.element); + Draggables.notify('onDrag', this, event); + + this.draw(pointer); + if(this.options.change) this.options.change(this); + + if(this.options.scroll) { + this.stopScrolling(); + + var p; + if (this.options.scroll == window) { + with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; } + } else { + p = Position.page(this.options.scroll); + p[0] += this.options.scroll.scrollLeft + Position.deltaX; + p[1] += this.options.scroll.scrollTop + Position.deltaY; + p.push(p[0]+this.options.scroll.offsetWidth); + p.push(p[1]+this.options.scroll.offsetHeight); + } + var speed = [0,0]; + if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity); + if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity); + if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity); + if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity); + this.startScrolling(speed); + } + + // fix AppleWebKit rendering + if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0); + + Event.stop(event); + }, + + finishDrag: function(event, success) { + this.dragging = false; + + if(this.options.ghosting) { + Position.relativize(this.element); + Element.remove(this._clone); + this._clone = null; + } + + if(success) Droppables.fire(event, this.element); + Draggables.notify('onEnd', this, event); + + var revert = this.options.revert; + if(revert && typeof revert == 'function') revert = revert(this.element); + + var d = this.currentDelta(); + if(revert && this.options.reverteffect) { + this.options.reverteffect(this.element, + d[1]-this.delta[1], d[0]-this.delta[0]); + } else { + this.delta = d; + } + + if(this.options.zindex) + this.element.style.zIndex = this.originalZ; + + if(this.options.endeffect) + this.options.endeffect(this.element); + + Draggables.deactivate(this); + Droppables.reset(); + }, + + keyPress: function(event) { + if(event.keyCode!=Event.KEY_ESC) return; + this.finishDrag(event, false); + Event.stop(event); + }, + + endDrag: function(event) { + if(!this.dragging) return; + this.stopScrolling(); + this.finishDrag(event, true); + Event.stop(event); + }, + + draw: function(point) { + var pos = Position.cumulativeOffset(this.element); + if(this.options.ghosting) { + var r = Position.realOffset(this.element); + pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY; + } + + var d = this.currentDelta(); + pos[0] -= d[0]; pos[1] -= d[1]; + + if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) { + pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft; + pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop; + } + + var p = [0,1].map(function(i){ + return (point[i]-pos[i]-this.offset[i]) + }.bind(this)); + + if(this.options.snap) { + if(typeof this.options.snap == 'function') { + p = this.options.snap(p[0],p[1],this); + } else { + if(this.options.snap instanceof Array) { + p = p.map( function(v, i) { + return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this)) + } else { + p = p.map( function(v) { + return Math.round(v/this.options.snap)*this.options.snap }.bind(this)) + } + }} + + var style = this.element.style; + if((!this.options.constraint) || (this.options.constraint=='horizontal')) + style.left = p[0] + "px"; + if((!this.options.constraint) || (this.options.constraint=='vertical')) + style.top = p[1] + "px"; + + if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering + }, + + stopScrolling: function() { + if(this.scrollInterval) { + clearInterval(this.scrollInterval); + this.scrollInterval = null; + Draggables._lastScrollPointer = null; + } + }, + + startScrolling: function(speed) { + if(!(speed[0] || speed[1])) return; + this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed]; + this.lastScrolled = new Date(); + this.scrollInterval = setInterval(this.scroll.bind(this), 10); + }, + + scroll: function() { + var current = new Date(); + var delta = current - this.lastScrolled; + this.lastScrolled = current; + if(this.options.scroll == window) { + with (this._getWindowScroll(this.options.scroll)) { + if (this.scrollSpeed[0] || this.scrollSpeed[1]) { + var d = delta / 1000; + this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] ); + } + } + } else { + this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; + this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; + } + + Position.prepare(); + Droppables.show(Draggables._lastPointer, this.element); + Draggables.notify('onDrag', this); + if (this._isScrollChild) { + Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer); + Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000; + Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000; + if (Draggables._lastScrollPointer[0] < 0) + Draggables._lastScrollPointer[0] = 0; + if (Draggables._lastScrollPointer[1] < 0) + Draggables._lastScrollPointer[1] = 0; + this.draw(Draggables._lastScrollPointer); + } + + if(this.options.change) this.options.change(this); + }, + + _getWindowScroll: function(w) { + var T, L, W, H; + with (w.document) { + if (w.document.documentElement && documentElement.scrollTop) { + T = documentElement.scrollTop; + L = documentElement.scrollLeft; + } else if (w.document.body) { + T = body.scrollTop; + L = body.scrollLeft; + } + if (w.innerWidth) { + W = w.innerWidth; + H = w.innerHeight; + } else if (w.document.documentElement && documentElement.clientWidth) { + W = documentElement.clientWidth; + H = documentElement.clientHeight; + } else { + W = body.offsetWidth; + H = body.offsetHeight + } + } + return { top: T, left: L, width: W, height: H }; + } +} + +/*--------------------------------------------------------------------------*/ + +var SortableObserver = Class.create(); +SortableObserver.prototype = { + initialize: function(element, observer) { + this.element = $(element); + this.observer = observer; + this.lastValue = Sortable.serialize(this.element); + }, + + onStart: function() { + this.lastValue = Sortable.serialize(this.element); + }, + + onEnd: function() { + Sortable.unmark(); + if(this.lastValue != Sortable.serialize(this.element)) + this.observer(this.element) + } +} + +var Sortable = { + SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/, + + sortables: {}, + + _findRootElement: function(element) { + while (element.tagName != "BODY") { + if(element.id && Sortable.sortables[element.id]) return element; + element = element.parentNode; + } + }, + + options: function(element) { + element = Sortable._findRootElement($(element)); + if(!element) return; + return Sortable.sortables[element.id]; + }, + + destroy: function(element){ + var s = Sortable.options(element); + + if(s) { + Draggables.removeObserver(s.element); + s.droppables.each(function(d){ Droppables.remove(d) }); + s.draggables.invoke('destroy'); + + delete Sortable.sortables[s.element.id]; + } + }, + + create: function(element) { + element = $(element); + var options = Object.extend({ + element: element, + tag: 'li', // assumes li children, override with tag: 'tagname' + dropOnEmpty: false, + tree: false, + treeTag: 'ul', + overlap: 'vertical', // one of 'vertical', 'horizontal' + constraint: 'vertical', // one of 'vertical', 'horizontal', false + containment: element, // also takes array of elements (or id's); or false + handle: false, // or a CSS class + only: false, + delay: 0, + hoverclass: null, + ghosting: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + format: this.SERIALIZE_RULE, + onChange: Prototype.emptyFunction, + onUpdate: Prototype.emptyFunction + }, arguments[1] || {}); + + // clear any old sortable with same element + this.destroy(element); + + // build options for the draggables + var options_for_draggable = { + revert: true, + scroll: options.scroll, + scrollSpeed: options.scrollSpeed, + scrollSensitivity: options.scrollSensitivity, + delay: options.delay, + ghosting: options.ghosting, + constraint: options.constraint, + handle: options.handle }; + + if(options.starteffect) + options_for_draggable.starteffect = options.starteffect; + + if(options.reverteffect) + options_for_draggable.reverteffect = options.reverteffect; + else + if(options.ghosting) options_for_draggable.reverteffect = function(element) { + element.style.top = 0; + element.style.left = 0; + }; + + if(options.endeffect) + options_for_draggable.endeffect = options.endeffect; + + if(options.zindex) + options_for_draggable.zindex = options.zindex; + + // build options for the droppables + var options_for_droppable = { + overlap: options.overlap, + containment: options.containment, + tree: options.tree, + hoverclass: options.hoverclass, + onHover: Sortable.onHover + } + + var options_for_tree = { + onHover: Sortable.onEmptyHover, + overlap: options.overlap, + containment: options.containment, + hoverclass: options.hoverclass + } + + // fix for gecko engine + Element.cleanWhitespace(element); + + options.draggables = []; + options.droppables = []; + + // drop on empty handling + if(options.dropOnEmpty || options.tree) { + Droppables.add(element, options_for_tree); + options.droppables.push(element); + } + + (this.findElements(element, options) || []).each( function(e) { + // handles are per-draggable + var handle = options.handle ? + $(e).down('.'+options.handle,0) : e; + options.draggables.push( + new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); + Droppables.add(e, options_for_droppable); + if(options.tree) e.treeNode = element; + options.droppables.push(e); + }); + + if(options.tree) { + (Sortable.findTreeElements(element, options) || []).each( function(e) { + Droppables.add(e, options_for_tree); + e.treeNode = element; + options.droppables.push(e); + }); + } + + // keep reference + this.sortables[element.id] = options; + + // for onupdate + Draggables.addObserver(new SortableObserver(element, options.onUpdate)); + + }, + + // return all suitable-for-sortable elements in a guaranteed order + findElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.tag); + }, + + findTreeElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.treeTag); + }, + + onHover: function(element, dropon, overlap) { + if(Element.isParent(dropon, element)) return; + + if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) { + return; + } else if(overlap>0.5) { + Sortable.mark(dropon, 'before'); + if(dropon.previousSibling != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, dropon); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } else { + Sortable.mark(dropon, 'after'); + var nextElement = dropon.nextSibling || null; + if(nextElement != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, nextElement); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } + }, + + onEmptyHover: function(element, dropon, overlap) { + var oldParentNode = element.parentNode; + var droponOptions = Sortable.options(dropon); + + if(!Element.isParent(dropon, element)) { + var index; + + var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only}); + var child = null; + + if(children) { + var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap); + + for (index = 0; index < children.length; index += 1) { + if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) { + offset -= Element.offsetSize (children[index], droponOptions.overlap); + } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) { + child = index + 1 < children.length ? children[index + 1] : null; + break; + } else { + child = children[index]; + break; + } + } + } + + dropon.insertBefore(element, child); + + Sortable.options(oldParentNode).onChange(element); + droponOptions.onChange(element); + } + }, + + unmark: function() { + if(Sortable._marker) Sortable._marker.hide(); + }, + + mark: function(dropon, position) { + // mark on ghosting only + var sortable = Sortable.options(dropon.parentNode); + if(sortable && !sortable.ghosting) return; + + if(!Sortable._marker) { + Sortable._marker = + ($('dropmarker') || Element.extend(document.createElement('DIV'))). + hide().addClassName('dropmarker').setStyle({position:'absolute'}); + document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); + } + var offsets = Position.cumulativeOffset(dropon); + Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'}); + + if(position=='after') + if(sortable.overlap == 'horizontal') + Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'}); + else + Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'}); + + Sortable._marker.show(); + }, + + _tree: function(element, options, parent) { + var children = Sortable.findElements(element, options) || []; + + for (var i = 0; i < children.length; ++i) { + var match = children[i].id.match(options.format); + + if (!match) continue; + + var child = { + id: encodeURIComponent(match ? match[1] : null), + element: element, + parent: parent, + children: [], + position: parent.children.length, + container: $(children[i]).down(options.treeTag) + } + + /* Get the element containing the children and recurse over it */ + if (child.container) + this._tree(child.container, options, child) + + parent.children.push (child); + } + + return parent; + }, + + tree: function(element) { + element = $(element); + var sortableOptions = this.options(element); + var options = Object.extend({ + tag: sortableOptions.tag, + treeTag: sortableOptions.treeTag, + only: sortableOptions.only, + name: element.id, + format: sortableOptions.format + }, arguments[1] || {}); + + var root = { + id: null, + parent: null, + children: [], + container: element, + position: 0 + } + + return Sortable._tree(element, options, root); + }, + + /* Construct a [i] index for a particular node */ + _constructIndex: function(node) { + var index = ''; + do { + if (node.id) index = '[' + node.position + ']' + index; + } while ((node = node.parent) != null); + return index; + }, + + sequence: function(element) { + element = $(element); + var options = Object.extend(this.options(element), arguments[1] || {}); + + return $(this.findElements(element, options) || []).map( function(item) { + return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; + }); + }, + + setSequence: function(element, new_sequence) { + element = $(element); + var options = Object.extend(this.options(element), arguments[2] || {}); + + var nodeMap = {}; + this.findElements(element, options).each( function(n) { + if (n.id.match(options.format)) + nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; + n.parentNode.removeChild(n); + }); + + new_sequence.each(function(ident) { + var n = nodeMap[ident]; + if (n) { + n[1].appendChild(n[0]); + delete nodeMap[ident]; + } + }); + }, + + serialize: function(element) { + element = $(element); + var options = Object.extend(Sortable.options(element), arguments[1] || {}); + var name = encodeURIComponent( + (arguments[1] && arguments[1].name) ? arguments[1].name : element.id); + + if (options.tree) { + return Sortable.tree(element, arguments[1]).children.map( function (item) { + return [name + Sortable._constructIndex(item) + "[id]=" + + encodeURIComponent(item.id)].concat(item.children.map(arguments.callee)); + }).flatten().join('&'); + } else { + return Sortable.sequence(element, arguments[1]).map( function(item) { + return name + "[]=" + encodeURIComponent(item); + }).join('&'); + } + } +} + +// Returns true if child is contained within element +Element.isParent = function(child, element) { + if (!child.parentNode || child == element) return false; + if (child.parentNode == element) return true; + return Element.isParent(child.parentNode, element); +} + +Element.findChildren = function(element, only, recursive, tagName) { + if(!element.hasChildNodes()) return null; + tagName = tagName.toUpperCase(); + if(only) only = [only].flatten(); + var elements = []; + $A(element.childNodes).each( function(e) { + if(e.tagName && e.tagName.toUpperCase()==tagName && + (!only || (Element.classNames(e).detect(function(v) { return only.include(v) })))) + elements.push(e); + if(recursive) { + var grandchildren = Element.findChildren(e, only, recursive, tagName); + if(grandchildren) elements.push(grandchildren); + } + }); + + return (elements.length>0 ? elements.flatten() : []); +} + +Element.offsetSize = function (element, type) { + return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')]; +} diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/effects.js b/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/effects.js new file mode 100644 index 0000000..3b02eda --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/effects.js @@ -0,0 +1,1088 @@ +// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// Contributors: +// Justin Palmer (http://encytemedia.com/) +// Mark Pilgrim (http://diveintomark.org/) +// Martin Bialasinki +// +// 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/ + +// converts rgb() and #xxx to #xxxxxx format, +// returns self (or first argument) if not convertable +String.prototype.parseColor = function() { + var color = '#'; + if(this.slice(0,4) == 'rgb(') { + var cols = this.slice(4,this.length-1).split(','); + var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); + } else { + if(this.slice(0,1) == '#') { + if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); + if(this.length==7) color = this.toLowerCase(); + } + } + return(color.length==7 ? color : (arguments[0] || this)); +} + +/*--------------------------------------------------------------------------*/ + +Element.collectTextNodes = function(element) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); + }).flatten().join(''); +} + +Element.collectTextNodesIgnoreClass = function(element, className) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? + Element.collectTextNodesIgnoreClass(node, className) : '')); + }).flatten().join(''); +} + +Element.setContentZoom = function(element, percent) { + element = $(element); + element.setStyle({fontSize: (percent/100) + 'em'}); + if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0); + return element; +} + +Element.getOpacity = function(element){ + element = $(element); + var opacity; + if (opacity = element.getStyle('opacity')) + return parseFloat(opacity); + if (opacity = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) + if(opacity[1]) return parseFloat(opacity[1]) / 100; + return 1.0; +} + +Element.setOpacity = function(element, value){ + element= $(element); + if (value == 1){ + element.setStyle({ opacity: + (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? + 0.999999 : 1.0 }); + if(/MSIE/.test(navigator.userAgent) && !window.opera) + element.setStyle({filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')}); + } else { + if(value < 0.00001) value = 0; + element.setStyle({opacity: value}); + if(/MSIE/.test(navigator.userAgent) && !window.opera) + element.setStyle( + { filter: element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') + + 'alpha(opacity='+value*100+')' }); + } + return element; +} + +Element.getInlineOpacity = function(element){ + return $(element).style.opacity || ''; +} + +Element.forceRerendering = function(element) { + try { + element = $(element); + var n = document.createTextNode(' '); + element.appendChild(n); + element.removeChild(n); + } catch(e) { } +}; + +/*--------------------------------------------------------------------------*/ + +Array.prototype.call = function() { + var args = arguments; + this.each(function(f){ f.apply(this, args) }); +} + +/*--------------------------------------------------------------------------*/ + +var Effect = { + _elementDoesNotExistError: { + name: 'ElementDoesNotExistError', + message: 'The specified DOM element does not exist, but is required for this effect to operate' + }, + tagifyText: function(element) { + if(typeof Builder == 'undefined') + throw("Effect.tagifyText requires including script.aculo.us' builder.js library"); + + var tagifyStyle = 'position:relative'; + if(/MSIE/.test(navigator.userAgent) && !window.opera) tagifyStyle += ';zoom:1'; + + element = $(element); + $A(element.childNodes).each( function(child) { + if(child.nodeType==3) { + child.nodeValue.toArray().each( function(character) { + element.insertBefore( + Builder.node('span',{style: tagifyStyle}, + character == ' ' ? String.fromCharCode(160) : character), + child); + }); + Element.remove(child); + } + }); + }, + multiple: function(element, effect) { + var elements; + if(((typeof element == 'object') || + (typeof element == 'function')) && + (element.length)) + elements = element; + else + elements = $(element).childNodes; + + var options = Object.extend({ + speed: 0.1, + delay: 0.0 + }, arguments[2] || {}); + var masterDelay = options.delay; + + $A(elements).each( function(element, index) { + new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay })); + }); + }, + PAIRS: { + 'slide': ['SlideDown','SlideUp'], + 'blind': ['BlindDown','BlindUp'], + 'appear': ['Appear','Fade'] + }, + toggle: function(element, effect) { + element = $(element); + effect = (effect || 'appear').toLowerCase(); + var options = Object.extend({ + queue: { position:'end', scope:(element.id || 'global'), limit: 1 } + }, arguments[2] || {}); + Effect[element.visible() ? + Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options); + } +}; + +var Effect2 = Effect; // deprecated + +/* ------------- transitions ------------- */ + +Effect.Transitions = { + linear: Prototype.K, + sinoidal: function(pos) { + return (-Math.cos(pos*Math.PI)/2) + 0.5; + }, + reverse: function(pos) { + return 1-pos; + }, + flicker: function(pos) { + return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4; + }, + wobble: function(pos) { + return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5; + }, + pulse: function(pos, pulses) { + pulses = pulses || 5; + return ( + Math.round((pos % (1/pulses)) * pulses) == 0 ? + ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) : + 1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) + ); + }, + none: function(pos) { + return 0; + }, + full: function(pos) { + return 1; + } +}; + +/* ------------- core effects ------------- */ + +Effect.ScopedQueue = Class.create(); +Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), { + initialize: function() { + this.effects = []; + this.interval = null; + }, + _each: function(iterator) { + this.effects._each(iterator); + }, + add: function(effect) { + var timestamp = new Date().getTime(); + + var position = (typeof effect.options.queue == 'string') ? + effect.options.queue : effect.options.queue.position; + + switch(position) { + case 'front': + // move unstarted effects after this effect + this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) { + e.startOn += effect.finishOn; + e.finishOn += effect.finishOn; + }); + break; + case 'with-last': + timestamp = this.effects.pluck('startOn').max() || timestamp; + break; + case 'end': + // start effect after last queued effect has finished + timestamp = this.effects.pluck('finishOn').max() || timestamp; + break; + } + + effect.startOn += timestamp; + effect.finishOn += timestamp; + + if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) + this.effects.push(effect); + + if(!this.interval) + this.interval = setInterval(this.loop.bind(this), 40); + }, + remove: function(effect) { + this.effects = this.effects.reject(function(e) { return e==effect }); + if(this.effects.length == 0) { + clearInterval(this.interval); + this.interval = null; + } + }, + loop: function() { + var timePos = new Date().getTime(); + this.effects.invoke('loop', timePos); + } +}); + +Effect.Queues = { + instances: $H(), + get: function(queueName) { + if(typeof queueName != 'string') return queueName; + + if(!this.instances[queueName]) + this.instances[queueName] = new Effect.ScopedQueue(); + + return this.instances[queueName]; + } +} +Effect.Queue = Effect.Queues.get('global'); + +Effect.DefaultOptions = { + transition: Effect.Transitions.sinoidal, + duration: 1.0, // seconds + fps: 25.0, // max. 25fps due to Effect.Queue implementation + sync: false, // true for combining + from: 0.0, + to: 1.0, + delay: 0.0, + queue: 'parallel' +} + +Effect.Base = function() {}; +Effect.Base.prototype = { + position: null, + start: function(options) { + this.options = Object.extend(Object.extend({},Effect.DefaultOptions), options || {}); + this.currentFrame = 0; + this.state = 'idle'; + this.startOn = this.options.delay*1000; + this.finishOn = this.startOn + (this.options.duration*1000); + this.event('beforeStart'); + if(!this.options.sync) + Effect.Queues.get(typeof this.options.queue == 'string' ? + 'global' : this.options.queue.scope).add(this); + }, + loop: function(timePos) { + if(timePos >= this.startOn) { + if(timePos >= this.finishOn) { + this.render(1.0); + this.cancel(); + this.event('beforeFinish'); + if(this.finish) this.finish(); + this.event('afterFinish'); + return; + } + var pos = (timePos - this.startOn) / (this.finishOn - this.startOn); + var frame = Math.round(pos * this.options.fps * this.options.duration); + if(frame > this.currentFrame) { + this.render(pos); + this.currentFrame = frame; + } + } + }, + render: function(pos) { + if(this.state == 'idle') { + this.state = 'running'; + this.event('beforeSetup'); + if(this.setup) this.setup(); + this.event('afterSetup'); + } + if(this.state == 'running') { + if(this.options.transition) pos = this.options.transition(pos); + pos *= (this.options.to-this.options.from); + pos += this.options.from; + this.position = pos; + this.event('beforeUpdate'); + if(this.update) this.update(pos); + this.event('afterUpdate'); + } + }, + cancel: function() { + if(!this.options.sync) + Effect.Queues.get(typeof this.options.queue == 'string' ? + 'global' : this.options.queue.scope).remove(this); + this.state = 'finished'; + }, + event: function(eventName) { + if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this); + if(this.options[eventName]) this.options[eventName](this); + }, + inspect: function() { + return '#'; + } +} + +Effect.Parallel = Class.create(); +Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), { + initialize: function(effects) { + this.effects = effects || []; + this.start(arguments[1]); + }, + update: function(position) { + this.effects.invoke('render', position); + }, + finish: function(position) { + this.effects.each( function(effect) { + effect.render(1.0); + effect.cancel(); + effect.event('beforeFinish'); + if(effect.finish) effect.finish(position); + effect.event('afterFinish'); + }); + } +}); + +Effect.Event = Class.create(); +Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), { + initialize: function() { + var options = Object.extend({ + duration: 0 + }, arguments[0] || {}); + this.start(options); + }, + update: Prototype.emptyFunction +}); + +Effect.Opacity = Class.create(); +Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + if(!this.element) throw(Effect._elementDoesNotExistError); + // make this work on IE on elements without 'layout' + if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout)) + this.element.setStyle({zoom: 1}); + var options = Object.extend({ + from: this.element.getOpacity() || 0.0, + to: 1.0 + }, arguments[1] || {}); + this.start(options); + }, + update: function(position) { + this.element.setOpacity(position); + } +}); + +Effect.Move = Class.create(); +Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + if(!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + x: 0, + y: 0, + mode: 'relative' + }, arguments[1] || {}); + this.start(options); + }, + setup: function() { + // Bug in Opera: Opera returns the "real" position of a static element or + // relative element that does not have top/left explicitly set. + // ==> Always set top and left for position relative elements in your stylesheets + // (to 0 if you do not need them) + this.element.makePositioned(); + this.originalLeft = parseFloat(this.element.getStyle('left') || '0'); + this.originalTop = parseFloat(this.element.getStyle('top') || '0'); + if(this.options.mode == 'absolute') { + // absolute movement, so we need to calc deltaX and deltaY + this.options.x = this.options.x - this.originalLeft; + this.options.y = this.options.y - this.originalTop; + } + }, + update: function(position) { + this.element.setStyle({ + left: Math.round(this.options.x * position + this.originalLeft) + 'px', + top: Math.round(this.options.y * position + this.originalTop) + 'px' + }); + } +}); + +// for backwards compatibility +Effect.MoveBy = function(element, toTop, toLeft) { + return new Effect.Move(element, + Object.extend({ x: toLeft, y: toTop }, arguments[3] || {})); +}; + +Effect.Scale = Class.create(); +Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), { + initialize: function(element, percent) { + this.element = $(element); + if(!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + scaleX: true, + scaleY: true, + scaleContent: true, + scaleFromCenter: false, + scaleMode: 'box', // 'box' or 'contents' or {} with provided values + scaleFrom: 100.0, + scaleTo: percent + }, arguments[2] || {}); + this.start(options); + }, + setup: function() { + this.restoreAfterFinish = this.options.restoreAfterFinish || false; + this.elementPositioning = this.element.getStyle('position'); + + this.originalStyle = {}; + ['top','left','width','height','fontSize'].each( function(k) { + this.originalStyle[k] = this.element.style[k]; + }.bind(this)); + + this.originalTop = this.element.offsetTop; + this.originalLeft = this.element.offsetLeft; + + var fontSize = this.element.getStyle('font-size') || '100%'; + ['em','px','%','pt'].each( function(fontSizeType) { + if(fontSize.indexOf(fontSizeType)>0) { + this.fontSize = parseFloat(fontSize); + this.fontSizeType = fontSizeType; + } + }.bind(this)); + + this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; + + this.dims = null; + if(this.options.scaleMode=='box') + this.dims = [this.element.offsetHeight, this.element.offsetWidth]; + if(/^content/.test(this.options.scaleMode)) + this.dims = [this.element.scrollHeight, this.element.scrollWidth]; + if(!this.dims) + this.dims = [this.options.scaleMode.originalHeight, + this.options.scaleMode.originalWidth]; + }, + update: function(position) { + var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); + if(this.options.scaleContent && this.fontSize) + this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); + this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); + }, + finish: function(position) { + if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle); + }, + setDimensions: function(height, width) { + var d = {}; + if(this.options.scaleX) d.width = Math.round(width) + 'px'; + if(this.options.scaleY) d.height = Math.round(height) + 'px'; + if(this.options.scaleFromCenter) { + var topd = (height - this.dims[0])/2; + var leftd = (width - this.dims[1])/2; + if(this.elementPositioning == 'absolute') { + if(this.options.scaleY) d.top = this.originalTop-topd + 'px'; + if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; + } else { + if(this.options.scaleY) d.top = -topd + 'px'; + if(this.options.scaleX) d.left = -leftd + 'px'; + } + } + this.element.setStyle(d); + } +}); + +Effect.Highlight = Class.create(); +Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + if(!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {}); + this.start(options); + }, + setup: function() { + // Prevent executing on elements not in the layout flow + if(this.element.getStyle('display')=='none') { this.cancel(); return; } + // Disable background image during the effect + this.oldStyle = { + backgroundImage: this.element.getStyle('background-image') }; + this.element.setStyle({backgroundImage: 'none'}); + if(!this.options.endcolor) + this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff'); + if(!this.options.restorecolor) + this.options.restorecolor = this.element.getStyle('background-color'); + // init color calculations + this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this)); + this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this)); + }, + update: function(position) { + this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){ + return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) }); + }, + finish: function() { + this.element.setStyle(Object.extend(this.oldStyle, { + backgroundColor: this.options.restorecolor + })); + } +}); + +Effect.ScrollTo = Class.create(); +Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + this.start(arguments[1] || {}); + }, + setup: function() { + Position.prepare(); + var offsets = Position.cumulativeOffset(this.element); + if(this.options.offset) offsets[1] += this.options.offset; + var max = window.innerHeight ? + window.height - window.innerHeight : + document.body.scrollHeight - + (document.documentElement.clientHeight ? + document.documentElement.clientHeight : document.body.clientHeight); + this.scrollStart = Position.deltaY; + this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart; + }, + update: function(position) { + Position.prepare(); + window.scrollTo(Position.deltaX, + this.scrollStart + (position*this.delta)); + } +}); + +/* ------------- combination effects ------------- */ + +Effect.Fade = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + var options = Object.extend({ + from: element.getOpacity() || 1.0, + to: 0.0, + afterFinishInternal: function(effect) { + if(effect.options.to!=0) return; + effect.element.hide().setStyle({opacity: oldOpacity}); + }}, arguments[1] || {}); + return new Effect.Opacity(element,options); +} + +Effect.Appear = function(element) { + element = $(element); + var options = Object.extend({ + from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0), + to: 1.0, + // force Safari to render floated elements properly + afterFinishInternal: function(effect) { + effect.element.forceRerendering(); + }, + beforeSetup: function(effect) { + effect.element.setOpacity(effect.options.from).show(); + }}, arguments[1] || {}); + return new Effect.Opacity(element,options); +} + +Effect.Puff = function(element) { + element = $(element); + var oldStyle = { + opacity: element.getInlineOpacity(), + position: element.getStyle('position'), + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height + }; + return new Effect.Parallel( + [ new Effect.Scale(element, 200, + { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], + Object.extend({ duration: 1.0, + beforeSetupInternal: function(effect) { + Position.absolutize(effect.effects[0].element) + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().setStyle(oldStyle); } + }, arguments[1] || {}) + ); +} + +Effect.BlindUp = function(element) { + element = $(element); + element.makeClipping(); + return new Effect.Scale(element, 0, + Object.extend({ scaleContent: false, + scaleX: false, + restoreAfterFinish: true, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping(); + } + }, arguments[1] || {}) + ); +} + +Effect.BlindDown = function(element) { + element = $(element); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: 0, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping(); + } + }, arguments[1] || {})); +} + +Effect.SwitchOff = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + return new Effect.Appear(element, Object.extend({ + duration: 0.4, + from: 0, + transition: Effect.Transitions.flicker, + afterFinishInternal: function(effect) { + new Effect.Scale(effect.element, 1, { + duration: 0.3, scaleFromCenter: true, + scaleX: false, scaleContent: false, restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makePositioned().makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity}); + } + }) + } + }, arguments[1] || {})); +} + +Effect.DropOut = function(element) { + element = $(element); + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left'), + opacity: element.getInlineOpacity() }; + return new Effect.Parallel( + [ new Effect.Move(element, {x: 0, y: 100, sync: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 }) ], + Object.extend( + { duration: 0.5, + beforeSetup: function(effect) { + effect.effects[0].element.makePositioned(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle); + } + }, arguments[1] || {})); +} + +Effect.Shake = function(element) { + element = $(element); + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left') }; + return new Effect.Move(element, + { x: 20, y: 0, duration: 0.05, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) { + effect.element.undoPositioned().setStyle(oldStyle); + }}) }}) }}) }}) }}) }}); +} + +Effect.SlideDown = function(element) { + element = $(element).cleanWhitespace(); + // SlideDown need to have the content of the element wrapped in a container element with fixed height! + var oldInnerBottom = element.down().getStyle('bottom'); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: window.opera ? 0 : 1, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makePositioned(); + effect.element.down().makePositioned(); + if(window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, + afterUpdateInternal: function(effect) { + effect.element.down().setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping().undoPositioned(); + effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); } + }, arguments[1] || {}) + ); +} + +Effect.SlideUp = function(element) { + element = $(element).cleanWhitespace(); + var oldInnerBottom = element.down().getStyle('bottom'); + return new Effect.Scale(element, window.opera ? 0 : 1, + Object.extend({ scaleContent: false, + scaleX: false, + scaleMode: 'box', + scaleFrom: 100, + restoreAfterFinish: true, + beforeStartInternal: function(effect) { + effect.element.makePositioned(); + effect.element.down().makePositioned(); + if(window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping().show(); + }, + afterUpdateInternal: function(effect) { + effect.element.down().setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom}); + effect.element.down().undoPositioned(); + } + }, arguments[1] || {}) + ); +} + +// Bug in opera makes the TD containing this element expand for a instance after finish +Effect.Squish = function(element) { + return new Effect.Scale(element, window.opera ? 1 : 0, { + restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping(); + } + }); +} + +Effect.Grow = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.full + }, arguments[1] || {}); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var initialMoveX, initialMoveY; + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + initialMoveX = initialMoveY = moveX = moveY = 0; + break; + case 'top-right': + initialMoveX = dims.width; + initialMoveY = moveY = 0; + moveX = -dims.width; + break; + case 'bottom-left': + initialMoveX = moveX = 0; + initialMoveY = dims.height; + moveY = -dims.height; + break; + case 'bottom-right': + initialMoveX = dims.width; + initialMoveY = dims.height; + moveX = -dims.width; + moveY = -dims.height; + break; + case 'center': + initialMoveX = dims.width / 2; + initialMoveY = dims.height / 2; + moveX = -dims.width / 2; + moveY = -dims.height / 2; + break; + } + + return new Effect.Move(element, { + x: initialMoveX, + y: initialMoveY, + duration: 0.01, + beforeSetup: function(effect) { + effect.element.hide().makeClipping().makePositioned(); + }, + afterFinishInternal: function(effect) { + new Effect.Parallel( + [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), + new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), + new Effect.Scale(effect.element, 100, { + scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, + sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true}) + ], Object.extend({ + beforeSetup: function(effect) { + effect.effects[0].element.setStyle({height: '0px'}).show(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); + } + }, options) + ) + } + }); +} + +Effect.Shrink = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.none + }, arguments[1] || {}); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + moveX = moveY = 0; + break; + case 'top-right': + moveX = dims.width; + moveY = 0; + break; + case 'bottom-left': + moveX = 0; + moveY = dims.height; + break; + case 'bottom-right': + moveX = dims.width; + moveY = dims.height; + break; + case 'center': + moveX = dims.width / 2; + moveY = dims.height / 2; + break; + } + + return new Effect.Parallel( + [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), + new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), + new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) + ], Object.extend({ + beforeStartInternal: function(effect) { + effect.effects[0].element.makePositioned().makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); } + }, options) + ); +} + +Effect.Pulsate = function(element) { + element = $(element); + var options = arguments[1] || {}; + var oldOpacity = element.getInlineOpacity(); + var transition = options.transition || Effect.Transitions.sinoidal; + var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) }; + reverser.bind(transition); + return new Effect.Opacity(element, + Object.extend(Object.extend({ duration: 2.0, from: 0, + afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } + }, options), {transition: reverser})); +} + +Effect.Fold = function(element) { + element = $(element); + var oldStyle = { + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height }; + element.makeClipping(); + return new Effect.Scale(element, 5, Object.extend({ + scaleContent: false, + scaleX: false, + afterFinishInternal: function(effect) { + new Effect.Scale(element, 1, { + scaleContent: false, + scaleY: false, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().setStyle(oldStyle); + } }); + }}, arguments[1] || {})); +}; + +Effect.Morph = Class.create(); +Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + if(!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + style: '' + }, arguments[1] || {}); + this.start(options); + }, + setup: function(){ + function parseColor(color){ + if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff'; + color = color.parseColor(); + return $R(0,2).map(function(i){ + return parseInt( color.slice(i*2+1,i*2+3), 16 ) + }); + } + this.transforms = this.options.style.parseStyle().map(function(property){ + var originalValue = this.element.getStyle(property[0]); + return $H({ + style: property[0], + originalValue: property[1].unit=='color' ? + parseColor(originalValue) : parseFloat(originalValue || 0), + targetValue: property[1].unit=='color' ? + parseColor(property[1].value) : property[1].value, + unit: property[1].unit + }); + }.bind(this)).reject(function(transform){ + return ( + (transform.originalValue == transform.targetValue) || + ( + transform.unit != 'color' && + (isNaN(transform.originalValue) || isNaN(transform.targetValue)) + ) + ) + }); + }, + update: function(position) { + var style = $H(), value = null; + this.transforms.each(function(transform){ + value = transform.unit=='color' ? + $R(0,2).inject('#',function(m,v,i){ + return m+(Math.round(transform.originalValue[i]+ + (transform.targetValue[i] - transform.originalValue[i])*position)).toColorPart() }) : + transform.originalValue + Math.round( + ((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit; + style[transform.style] = value; + }); + this.element.setStyle(style); + } +}); + +Effect.Transform = Class.create(); +Object.extend(Effect.Transform.prototype, { + initialize: function(tracks){ + this.tracks = []; + this.options = arguments[1] || {}; + this.addTracks(tracks); + }, + addTracks: function(tracks){ + tracks.each(function(track){ + var data = $H(track).values().first(); + this.tracks.push($H({ + ids: $H(track).keys().first(), + effect: Effect.Morph, + options: { style: data } + })); + }.bind(this)); + return this; + }, + play: function(){ + return new Effect.Parallel( + this.tracks.map(function(track){ + var elements = [$(track.ids) || $$(track.ids)].flatten(); + return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) }); + }).flatten(), + this.options + ); + } +}); + +Element.CSS_PROPERTIES = ['azimuth', 'backgroundAttachment', 'backgroundColor', 'backgroundImage', + 'backgroundPosition', 'backgroundRepeat', 'borderBottomColor', 'borderBottomStyle', + 'borderBottomWidth', 'borderCollapse', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', + 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderSpacing', 'borderTopColor', + 'borderTopStyle', 'borderTopWidth', 'bottom', 'captionSide', 'clear', 'clip', 'color', 'content', + 'counterIncrement', 'counterReset', 'cssFloat', 'cueAfter', 'cueBefore', 'cursor', 'direction', + 'display', 'elevation', 'emptyCells', 'fontFamily', 'fontSize', 'fontSizeAdjust', 'fontStretch', + 'fontStyle', 'fontVariant', 'fontWeight', 'height', 'left', 'letterSpacing', 'lineHeight', + 'listStyleImage', 'listStylePosition', 'listStyleType', 'marginBottom', 'marginLeft', 'marginRight', + 'marginTop', 'markerOffset', 'marks', 'maxHeight', 'maxWidth', 'minHeight', 'minWidth', 'opacity', + 'orphans', 'outlineColor', 'outlineOffset', 'outlineStyle', 'outlineWidth', 'overflowX', 'overflowY', + 'paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop', 'page', 'pageBreakAfter', 'pageBreakBefore', + 'pageBreakInside', 'pauseAfter', 'pauseBefore', 'pitch', 'pitchRange', 'position', 'quotes', + 'richness', 'right', 'size', 'speakHeader', 'speakNumeral', 'speakPunctuation', 'speechRate', 'stress', + 'tableLayout', 'textAlign', 'textDecoration', 'textIndent', 'textShadow', 'textTransform', 'top', + 'unicodeBidi', 'verticalAlign', 'visibility', 'voiceFamily', 'volume', 'whiteSpace', 'widows', + 'width', 'wordSpacing', 'zIndex']; + +Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/; + +String.prototype.parseStyle = function(){ + var element = Element.extend(document.createElement('div')); + element.innerHTML = '

    '; + var style = element.down().style, styleRules = $H(); + + Element.CSS_PROPERTIES.each(function(property){ + if(style[property]) styleRules[property] = style[property]; + }); + + var result = $H(); + + styleRules.each(function(pair){ + var property = pair[0], value = pair[1], unit = null; + + if(value.parseColor('#zzzzzz') != '#zzzzzz') { + value = value.parseColor(); + unit = 'color'; + } else if(Element.CSS_LENGTH.test(value)) + var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/), + value = parseFloat(components[1]), unit = (components.length == 3) ? components[2] : null; + + result[property.underscore().dasherize()] = $H({ value:value, unit:unit }); + }.bind(this)); + + return result; +}; + +Element.morph = function(element, style) { + new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {})); + return element; +}; + +['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom', + 'collectTextNodes','collectTextNodesIgnoreClass','morph'].each( + function(f) { Element.Methods[f] = Element[f]; } +); + +Element.Methods.visualEffect = function(element, effect, options) { + s = effect.gsub(/_/, '-').camelize(); + effect_class = s.charAt(0).toUpperCase() + s.substring(1); + new Effect[effect_class](element, options); + return $(element); +}; + +Element.addMethods(); \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/prototype.js b/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/prototype.js new file mode 100644 index 0000000..5058221 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/javascripts/prototype.js @@ -0,0 +1,2515 @@ +/* Prototype JavaScript framework, version 1.5.0 + * (c) 2005-2007 Sam Stephenson + * + * Prototype is freely distributable under the terms of an MIT-style license. + * For details, see the Prototype web site: http://prototype.conio.net/ + * +/*--------------------------------------------------------------------------*/ + +var Prototype = { + Version: '1.5.0', + BrowserFeatures: { + XPath: !!document.evaluate + }, + + ScriptFragment: '(?:)((\n|\r|.)*?)(?:<\/script>)', + emptyFunction: function() {}, + K: function(x) { return x } +} + +var Class = { + create: function() { + return function() { + this.initialize.apply(this, arguments); + } + } +} + +var Abstract = new Object(); + +Object.extend = function(destination, source) { + for (var property in source) { + destination[property] = source[property]; + } + return destination; +} + +Object.extend(Object, { + inspect: function(object) { + try { + if (object === undefined) return 'undefined'; + if (object === null) return 'null'; + return object.inspect ? object.inspect() : object.toString(); + } catch (e) { + if (e instanceof RangeError) return '...'; + throw e; + } + }, + + keys: function(object) { + var keys = []; + for (var property in object) + keys.push(property); + return keys; + }, + + values: function(object) { + var values = []; + for (var property in object) + values.push(object[property]); + return values; + }, + + clone: function(object) { + return Object.extend({}, object); + } +}); + +Function.prototype.bind = function() { + var __method = this, args = $A(arguments), object = args.shift(); + return function() { + return __method.apply(object, args.concat($A(arguments))); + } +} + +Function.prototype.bindAsEventListener = function(object) { + var __method = this, args = $A(arguments), object = args.shift(); + return function(event) { + return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments))); + } +} + +Object.extend(Number.prototype, { + toColorPart: function() { + var digits = this.toString(16); + if (this < 16) return '0' + digits; + return digits; + }, + + succ: function() { + return this + 1; + }, + + times: function(iterator) { + $R(0, this, true).each(iterator); + return this; + } +}); + +var Try = { + these: function() { + var returnValue; + + for (var i = 0, length = arguments.length; i < length; i++) { + var lambda = arguments[i]; + try { + returnValue = lambda(); + break; + } catch (e) {} + } + + return returnValue; + } +} + +/*--------------------------------------------------------------------------*/ + +var PeriodicalExecuter = Class.create(); +PeriodicalExecuter.prototype = { + initialize: function(callback, frequency) { + this.callback = callback; + this.frequency = frequency; + this.currentlyExecuting = false; + + this.registerCallback(); + }, + + registerCallback: function() { + this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + stop: function() { + if (!this.timer) return; + clearInterval(this.timer); + this.timer = null; + }, + + onTimerEvent: function() { + if (!this.currentlyExecuting) { + try { + this.currentlyExecuting = true; + this.callback(this); + } finally { + this.currentlyExecuting = false; + } + } + } +} +String.interpret = function(value){ + return value == null ? '' : String(value); +} + +Object.extend(String.prototype, { + gsub: function(pattern, replacement) { + var result = '', source = this, match; + replacement = arguments.callee.prepareReplacement(replacement); + + while (source.length > 0) { + if (match = source.match(pattern)) { + result += source.slice(0, match.index); + result += String.interpret(replacement(match)); + source = source.slice(match.index + match[0].length); + } else { + result += source, source = ''; + } + } + return result; + }, + + sub: function(pattern, replacement, count) { + replacement = this.gsub.prepareReplacement(replacement); + count = count === undefined ? 1 : count; + + return this.gsub(pattern, function(match) { + if (--count < 0) return match[0]; + return replacement(match); + }); + }, + + scan: function(pattern, iterator) { + this.gsub(pattern, iterator); + return this; + }, + + truncate: function(length, truncation) { + length = length || 30; + truncation = truncation === undefined ? '...' : truncation; + return this.length > length ? + this.slice(0, length - truncation.length) + truncation : this; + }, + + strip: function() { + return this.replace(/^\s+/, '').replace(/\s+$/, ''); + }, + + stripTags: function() { + return this.replace(/<\/?[^>]+>/gi, ''); + }, + + stripScripts: function() { + return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); + }, + + extractScripts: function() { + var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); + var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); + return (this.match(matchAll) || []).map(function(scriptTag) { + return (scriptTag.match(matchOne) || ['', ''])[1]; + }); + }, + + evalScripts: function() { + return this.extractScripts().map(function(script) { return eval(script) }); + }, + + escapeHTML: function() { + var div = document.createElement('div'); + var text = document.createTextNode(this); + div.appendChild(text); + return div.innerHTML; + }, + + unescapeHTML: function() { + var div = document.createElement('div'); + div.innerHTML = this.stripTags(); + return div.childNodes[0] ? (div.childNodes.length > 1 ? + $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) : + div.childNodes[0].nodeValue) : ''; + }, + + toQueryParams: function(separator) { + var match = this.strip().match(/([^?#]*)(#.*)?$/); + if (!match) return {}; + + return match[1].split(separator || '&').inject({}, function(hash, pair) { + if ((pair = pair.split('='))[0]) { + var name = decodeURIComponent(pair[0]); + var value = pair[1] ? decodeURIComponent(pair[1]) : undefined; + + if (hash[name] !== undefined) { + if (hash[name].constructor != Array) + hash[name] = [hash[name]]; + if (value) hash[name].push(value); + } + else hash[name] = value; + } + return hash; + }); + }, + + toArray: function() { + return this.split(''); + }, + + succ: function() { + return this.slice(0, this.length - 1) + + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); + }, + + camelize: function() { + var parts = this.split('-'), len = parts.length; + if (len == 1) return parts[0]; + + var camelized = this.charAt(0) == '-' + ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) + : parts[0]; + + for (var i = 1; i < len; i++) + camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); + + return camelized; + }, + + capitalize: function(){ + return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); + }, + + underscore: function() { + return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase(); + }, + + dasherize: function() { + return this.gsub(/_/,'-'); + }, + + inspect: function(useDoubleQuotes) { + var escapedString = this.replace(/\\/g, '\\\\'); + if (useDoubleQuotes) + return '"' + escapedString.replace(/"/g, '\\"') + '"'; + else + return "'" + escapedString.replace(/'/g, '\\\'') + "'"; + } +}); + +String.prototype.gsub.prepareReplacement = function(replacement) { + if (typeof replacement == 'function') return replacement; + var template = new Template(replacement); + return function(match) { return template.evaluate(match) }; +} + +String.prototype.parseQuery = String.prototype.toQueryParams; + +var Template = Class.create(); +Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; +Template.prototype = { + initialize: function(template, pattern) { + this.template = template.toString(); + this.pattern = pattern || Template.Pattern; + }, + + evaluate: function(object) { + return this.template.gsub(this.pattern, function(match) { + var before = match[1]; + if (before == '\\') return match[2]; + return before + String.interpret(object[match[3]]); + }); + } +} + +var $break = new Object(); +var $continue = new Object(); + +var Enumerable = { + each: function(iterator) { + var index = 0; + try { + this._each(function(value) { + try { + iterator(value, index++); + } catch (e) { + if (e != $continue) throw e; + } + }); + } catch (e) { + if (e != $break) throw e; + } + return this; + }, + + eachSlice: function(number, iterator) { + var index = -number, slices = [], array = this.toArray(); + while ((index += number) < array.length) + slices.push(array.slice(index, index+number)); + return slices.map(iterator); + }, + + all: function(iterator) { + var result = true; + this.each(function(value, index) { + result = result && !!(iterator || Prototype.K)(value, index); + if (!result) throw $break; + }); + return result; + }, + + any: function(iterator) { + var result = false; + this.each(function(value, index) { + if (result = !!(iterator || Prototype.K)(value, index)) + throw $break; + }); + return result; + }, + + collect: function(iterator) { + var results = []; + this.each(function(value, index) { + results.push((iterator || Prototype.K)(value, index)); + }); + return results; + }, + + detect: function(iterator) { + var result; + this.each(function(value, index) { + if (iterator(value, index)) { + result = value; + throw $break; + } + }); + return result; + }, + + findAll: function(iterator) { + var results = []; + this.each(function(value, index) { + if (iterator(value, index)) + results.push(value); + }); + return results; + }, + + grep: function(pattern, iterator) { + var results = []; + this.each(function(value, index) { + var stringValue = value.toString(); + if (stringValue.match(pattern)) + results.push((iterator || Prototype.K)(value, index)); + }) + return results; + }, + + include: function(object) { + var found = false; + this.each(function(value) { + if (value == object) { + found = true; + throw $break; + } + }); + return found; + }, + + inGroupsOf: function(number, fillWith) { + fillWith = fillWith === undefined ? null : fillWith; + return this.eachSlice(number, function(slice) { + while(slice.length < number) slice.push(fillWith); + return slice; + }); + }, + + inject: function(memo, iterator) { + this.each(function(value, index) { + memo = iterator(memo, value, index); + }); + return memo; + }, + + invoke: function(method) { + var args = $A(arguments).slice(1); + return this.map(function(value) { + return value[method].apply(value, args); + }); + }, + + max: function(iterator) { + var result; + this.each(function(value, index) { + value = (iterator || Prototype.K)(value, index); + if (result == undefined || value >= result) + result = value; + }); + return result; + }, + + min: function(iterator) { + var result; + this.each(function(value, index) { + value = (iterator || Prototype.K)(value, index); + if (result == undefined || value < result) + result = value; + }); + return result; + }, + + partition: function(iterator) { + var trues = [], falses = []; + this.each(function(value, index) { + ((iterator || Prototype.K)(value, index) ? + trues : falses).push(value); + }); + return [trues, falses]; + }, + + pluck: function(property) { + var results = []; + this.each(function(value, index) { + results.push(value[property]); + }); + return results; + }, + + reject: function(iterator) { + var results = []; + this.each(function(value, index) { + if (!iterator(value, index)) + results.push(value); + }); + return results; + }, + + sortBy: function(iterator) { + return this.map(function(value, index) { + return {value: value, criteria: iterator(value, index)}; + }).sort(function(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }).pluck('value'); + }, + + toArray: function() { + return this.map(); + }, + + zip: function() { + var iterator = Prototype.K, args = $A(arguments); + if (typeof args.last() == 'function') + iterator = args.pop(); + + var collections = [this].concat(args).map($A); + return this.map(function(value, index) { + return iterator(collections.pluck(index)); + }); + }, + + size: function() { + return this.toArray().length; + }, + + inspect: function() { + return '#'; + } +} + +Object.extend(Enumerable, { + map: Enumerable.collect, + find: Enumerable.detect, + select: Enumerable.findAll, + member: Enumerable.include, + entries: Enumerable.toArray +}); +var $A = Array.from = function(iterable) { + if (!iterable) return []; + if (iterable.toArray) { + return iterable.toArray(); + } else { + var results = []; + for (var i = 0, length = iterable.length; i < length; i++) + results.push(iterable[i]); + return results; + } +} + +Object.extend(Array.prototype, Enumerable); + +if (!Array.prototype._reverse) + Array.prototype._reverse = Array.prototype.reverse; + +Object.extend(Array.prototype, { + _each: function(iterator) { + for (var i = 0, length = this.length; i < length; i++) + iterator(this[i]); + }, + + clear: function() { + this.length = 0; + return this; + }, + + first: function() { + return this[0]; + }, + + last: function() { + return this[this.length - 1]; + }, + + compact: function() { + return this.select(function(value) { + return value != null; + }); + }, + + flatten: function() { + return this.inject([], function(array, value) { + return array.concat(value && value.constructor == Array ? + value.flatten() : [value]); + }); + }, + + without: function() { + var values = $A(arguments); + return this.select(function(value) { + return !values.include(value); + }); + }, + + indexOf: function(object) { + for (var i = 0, length = this.length; i < length; i++) + if (this[i] == object) return i; + return -1; + }, + + reverse: function(inline) { + return (inline !== false ? this : this.toArray())._reverse(); + }, + + reduce: function() { + return this.length > 1 ? this : this[0]; + }, + + uniq: function() { + return this.inject([], function(array, value) { + return array.include(value) ? array : array.concat([value]); + }); + }, + + clone: function() { + return [].concat(this); + }, + + size: function() { + return this.length; + }, + + inspect: function() { + return '[' + this.map(Object.inspect).join(', ') + ']'; + } +}); + +Array.prototype.toArray = Array.prototype.clone; + +function $w(string){ + string = string.strip(); + return string ? string.split(/\s+/) : []; +} + +if(window.opera){ + Array.prototype.concat = function(){ + var array = []; + for(var i = 0, length = this.length; i < length; i++) array.push(this[i]); + for(var i = 0, length = arguments.length; i < length; i++) { + if(arguments[i].constructor == Array) { + for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) + array.push(arguments[i][j]); + } else { + array.push(arguments[i]); + } + } + return array; + } +} +var Hash = function(obj) { + Object.extend(this, obj || {}); +}; + +Object.extend(Hash, { + toQueryString: function(obj) { + var parts = []; + + this.prototype._each.call(obj, function(pair) { + if (!pair.key) return; + + if (pair.value && pair.value.constructor == Array) { + var values = pair.value.compact(); + if (values.length < 2) pair.value = values.reduce(); + else { + key = encodeURIComponent(pair.key); + values.each(function(value) { + value = value != undefined ? encodeURIComponent(value) : ''; + parts.push(key + '=' + encodeURIComponent(value)); + }); + return; + } + } + if (pair.value == undefined) pair[1] = ''; + parts.push(pair.map(encodeURIComponent).join('=')); + }); + + return parts.join('&'); + } +}); + +Object.extend(Hash.prototype, Enumerable); +Object.extend(Hash.prototype, { + _each: function(iterator) { + for (var key in this) { + var value = this[key]; + if (value && value == Hash.prototype[key]) continue; + + var pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } + }, + + keys: function() { + return this.pluck('key'); + }, + + values: function() { + return this.pluck('value'); + }, + + merge: function(hash) { + return $H(hash).inject(this, function(mergedHash, pair) { + mergedHash[pair.key] = pair.value; + return mergedHash; + }); + }, + + remove: function() { + var result; + for(var i = 0, length = arguments.length; i < length; i++) { + var value = this[arguments[i]]; + if (value !== undefined){ + if (result === undefined) result = value; + else { + if (result.constructor != Array) result = [result]; + result.push(value) + } + } + delete this[arguments[i]]; + } + return result; + }, + + toQueryString: function() { + return Hash.toQueryString(this); + }, + + inspect: function() { + return '#'; + } +}); + +function $H(object) { + if (object && object.constructor == Hash) return object; + return new Hash(object); +}; +ObjectRange = Class.create(); +Object.extend(ObjectRange.prototype, Enumerable); +Object.extend(ObjectRange.prototype, { + initialize: function(start, end, exclusive) { + this.start = start; + this.end = end; + this.exclusive = exclusive; + }, + + _each: function(iterator) { + var value = this.start; + while (this.include(value)) { + iterator(value); + value = value.succ(); + } + }, + + include: function(value) { + if (value < this.start) + return false; + if (this.exclusive) + return value < this.end; + return value <= this.end; + } +}); + +var $R = function(start, end, exclusive) { + return new ObjectRange(start, end, exclusive); +} + +var Ajax = { + getTransport: function() { + return Try.these( + function() {return new XMLHttpRequest()}, + function() {return new ActiveXObject('Msxml2.XMLHTTP')}, + function() {return new ActiveXObject('Microsoft.XMLHTTP')} + ) || false; + }, + + activeRequestCount: 0 +} + +Ajax.Responders = { + responders: [], + + _each: function(iterator) { + this.responders._each(iterator); + }, + + register: function(responder) { + if (!this.include(responder)) + this.responders.push(responder); + }, + + unregister: function(responder) { + this.responders = this.responders.without(responder); + }, + + dispatch: function(callback, request, transport, json) { + this.each(function(responder) { + if (typeof responder[callback] == 'function') { + try { + responder[callback].apply(responder, [request, transport, json]); + } catch (e) {} + } + }); + } +}; + +Object.extend(Ajax.Responders, Enumerable); + +Ajax.Responders.register({ + onCreate: function() { + Ajax.activeRequestCount++; + }, + onComplete: function() { + Ajax.activeRequestCount--; + } +}); + +Ajax.Base = function() {}; +Ajax.Base.prototype = { + setOptions: function(options) { + this.options = { + method: 'post', + asynchronous: true, + contentType: 'application/x-www-form-urlencoded', + encoding: 'UTF-8', + parameters: '' + } + Object.extend(this.options, options || {}); + + this.options.method = this.options.method.toLowerCase(); + if (typeof this.options.parameters == 'string') + this.options.parameters = this.options.parameters.toQueryParams(); + } +} + +Ajax.Request = Class.create(); +Ajax.Request.Events = + ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; + +Ajax.Request.prototype = Object.extend(new Ajax.Base(), { + _complete: false, + + initialize: function(url, options) { + this.transport = Ajax.getTransport(); + this.setOptions(options); + this.request(url); + }, + + request: function(url) { + this.url = url; + this.method = this.options.method; + var params = this.options.parameters; + + if (!['get', 'post'].include(this.method)) { + // simulate other verbs over post + params['_method'] = this.method; + this.method = 'post'; + } + + params = Hash.toQueryString(params); + if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_=' + + // when GET, append parameters to URL + if (this.method == 'get' && params) + this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params; + + try { + Ajax.Responders.dispatch('onCreate', this, this.transport); + + this.transport.open(this.method.toUpperCase(), this.url, + this.options.asynchronous); + + if (this.options.asynchronous) + setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10); + + this.transport.onreadystatechange = this.onStateChange.bind(this); + this.setRequestHeaders(); + + var body = this.method == 'post' ? (this.options.postBody || params) : null; + + this.transport.send(body); + + /* Force Firefox to handle ready state 4 for synchronous requests */ + if (!this.options.asynchronous && this.transport.overrideMimeType) + this.onStateChange(); + + } + catch (e) { + this.dispatchException(e); + } + }, + + onStateChange: function() { + var readyState = this.transport.readyState; + if (readyState > 1 && !((readyState == 4) && this._complete)) + this.respondToReadyState(this.transport.readyState); + }, + + setRequestHeaders: function() { + var headers = { + 'X-Requested-With': 'XMLHttpRequest', + 'X-Prototype-Version': Prototype.Version, + 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' + }; + + if (this.method == 'post') { + headers['Content-type'] = this.options.contentType + + (this.options.encoding ? '; charset=' + this.options.encoding : ''); + + /* Force "Connection: close" for older Mozilla browsers to work + * around a bug where XMLHttpRequest sends an incorrect + * Content-length header. See Mozilla Bugzilla #246651. + */ + if (this.transport.overrideMimeType && + (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) + headers['Connection'] = 'close'; + } + + // user-defined headers + if (typeof this.options.requestHeaders == 'object') { + var extras = this.options.requestHeaders; + + if (typeof extras.push == 'function') + for (var i = 0, length = extras.length; i < length; i += 2) + headers[extras[i]] = extras[i+1]; + else + $H(extras).each(function(pair) { headers[pair.key] = pair.value }); + } + + for (var name in headers) + this.transport.setRequestHeader(name, headers[name]); + }, + + success: function() { + return !this.transport.status + || (this.transport.status >= 200 && this.transport.status < 300); + }, + + respondToReadyState: function(readyState) { + var state = Ajax.Request.Events[readyState]; + var transport = this.transport, json = this.evalJSON(); + + if (state == 'Complete') { + try { + this._complete = true; + (this.options['on' + this.transport.status] + || this.options['on' + (this.success() ? 'Success' : 'Failure')] + || Prototype.emptyFunction)(transport, json); + } catch (e) { + this.dispatchException(e); + } + + if ((this.getHeader('Content-type') || 'text/javascript').strip(). + match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i)) + this.evalResponse(); + } + + try { + (this.options['on' + state] || Prototype.emptyFunction)(transport, json); + Ajax.Responders.dispatch('on' + state, this, transport, json); + } catch (e) { + this.dispatchException(e); + } + + if (state == 'Complete') { + // avoid memory leak in MSIE: clean up + this.transport.onreadystatechange = Prototype.emptyFunction; + } + }, + + getHeader: function(name) { + try { + return this.transport.getResponseHeader(name); + } catch (e) { return null } + }, + + evalJSON: function() { + try { + var json = this.getHeader('X-JSON'); + return json ? eval('(' + json + ')') : null; + } catch (e) { return null } + }, + + evalResponse: function() { + try { + return eval(this.transport.responseText); + } catch (e) { + this.dispatchException(e); + } + }, + + dispatchException: function(exception) { + (this.options.onException || Prototype.emptyFunction)(this, exception); + Ajax.Responders.dispatch('onException', this, exception); + } +}); + +Ajax.Updater = Class.create(); + +Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), { + initialize: function(container, url, options) { + this.container = { + success: (container.success || container), + failure: (container.failure || (container.success ? null : container)) + } + + this.transport = Ajax.getTransport(); + this.setOptions(options); + + var onComplete = this.options.onComplete || Prototype.emptyFunction; + this.options.onComplete = (function(transport, param) { + this.updateContent(); + onComplete(transport, param); + }).bind(this); + + this.request(url); + }, + + updateContent: function() { + var receiver = this.container[this.success() ? 'success' : 'failure']; + var response = this.transport.responseText; + + if (!this.options.evalScripts) response = response.stripScripts(); + + if (receiver = $(receiver)) { + if (this.options.insertion) + new this.options.insertion(receiver, response); + else + receiver.update(response); + } + + if (this.success()) { + if (this.onComplete) + setTimeout(this.onComplete.bind(this), 10); + } + } +}); + +Ajax.PeriodicalUpdater = Class.create(); +Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), { + initialize: function(container, url, options) { + this.setOptions(options); + this.onComplete = this.options.onComplete; + + this.frequency = (this.options.frequency || 2); + this.decay = (this.options.decay || 1); + + this.updater = {}; + this.container = container; + this.url = url; + + this.start(); + }, + + start: function() { + this.options.onComplete = this.updateComplete.bind(this); + this.onTimerEvent(); + }, + + stop: function() { + this.updater.options.onComplete = undefined; + clearTimeout(this.timer); + (this.onComplete || Prototype.emptyFunction).apply(this, arguments); + }, + + updateComplete: function(request) { + if (this.options.decay) { + this.decay = (request.responseText == this.lastText ? + this.decay * this.options.decay : 1); + + this.lastText = request.responseText; + } + this.timer = setTimeout(this.onTimerEvent.bind(this), + this.decay * this.frequency * 1000); + }, + + onTimerEvent: function() { + this.updater = new Ajax.Updater(this.container, this.url, this.options); + } +}); +function $(element) { + if (arguments.length > 1) { + for (var i = 0, elements = [], length = arguments.length; i < length; i++) + elements.push($(arguments[i])); + return elements; + } + if (typeof element == 'string') + element = document.getElementById(element); + return Element.extend(element); +} + +if (Prototype.BrowserFeatures.XPath) { + document._getElementsByXPath = function(expression, parentElement) { + var results = []; + var query = document.evaluate(expression, $(parentElement) || document, + null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + for (var i = 0, length = query.snapshotLength; i < length; i++) + results.push(query.snapshotItem(i)); + return results; + }; +} + +document.getElementsByClassName = function(className, parentElement) { + if (Prototype.BrowserFeatures.XPath) { + var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]"; + return document._getElementsByXPath(q, parentElement); + } else { + var children = ($(parentElement) || document.body).getElementsByTagName('*'); + var elements = [], child; + for (var i = 0, length = children.length; i < length; i++) { + child = children[i]; + if (Element.hasClassName(child, className)) + elements.push(Element.extend(child)); + } + return elements; + } +}; + +/*--------------------------------------------------------------------------*/ + +if (!window.Element) + var Element = new Object(); + +Element.extend = function(element) { + if (!element || _nativeExtensions || element.nodeType == 3) return element; + + if (!element._extended && element.tagName && element != window) { + var methods = Object.clone(Element.Methods), cache = Element.extend.cache; + + if (element.tagName == 'FORM') + Object.extend(methods, Form.Methods); + if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName)) + Object.extend(methods, Form.Element.Methods); + + Object.extend(methods, Element.Methods.Simulated); + + for (var property in methods) { + var value = methods[property]; + if (typeof value == 'function' && !(property in element)) + element[property] = cache.findOrStore(value); + } + } + + element._extended = true; + return element; +}; + +Element.extend.cache = { + findOrStore: function(value) { + return this[value] = this[value] || function() { + return value.apply(null, [this].concat($A(arguments))); + } + } +}; + +Element.Methods = { + visible: function(element) { + return $(element).style.display != 'none'; + }, + + toggle: function(element) { + element = $(element); + Element[Element.visible(element) ? 'hide' : 'show'](element); + return element; + }, + + hide: function(element) { + $(element).style.display = 'none'; + return element; + }, + + show: function(element) { + $(element).style.display = ''; + return element; + }, + + remove: function(element) { + element = $(element); + element.parentNode.removeChild(element); + return element; + }, + + update: function(element, html) { + html = typeof html == 'undefined' ? '' : html.toString(); + $(element).innerHTML = html.stripScripts(); + setTimeout(function() {html.evalScripts()}, 10); + return element; + }, + + replace: function(element, html) { + element = $(element); + html = typeof html == 'undefined' ? '' : html.toString(); + if (element.outerHTML) { + element.outerHTML = html.stripScripts(); + } else { + var range = element.ownerDocument.createRange(); + range.selectNodeContents(element); + element.parentNode.replaceChild( + range.createContextualFragment(html.stripScripts()), element); + } + setTimeout(function() {html.evalScripts()}, 10); + return element; + }, + + inspect: function(element) { + element = $(element); + var result = '<' + element.tagName.toLowerCase(); + $H({'id': 'id', 'className': 'class'}).each(function(pair) { + var property = pair.first(), attribute = pair.last(); + var value = (element[property] || '').toString(); + if (value) result += ' ' + attribute + '=' + value.inspect(true); + }); + return result + '>'; + }, + + recursivelyCollect: function(element, property) { + element = $(element); + var elements = []; + while (element = element[property]) + if (element.nodeType == 1) + elements.push(Element.extend(element)); + return elements; + }, + + ancestors: function(element) { + return $(element).recursivelyCollect('parentNode'); + }, + + descendants: function(element) { + return $A($(element).getElementsByTagName('*')); + }, + + immediateDescendants: function(element) { + if (!(element = $(element).firstChild)) return []; + while (element && element.nodeType != 1) element = element.nextSibling; + if (element) return [element].concat($(element).nextSiblings()); + return []; + }, + + previousSiblings: function(element) { + return $(element).recursivelyCollect('previousSibling'); + }, + + nextSiblings: function(element) { + return $(element).recursivelyCollect('nextSibling'); + }, + + siblings: function(element) { + element = $(element); + return element.previousSiblings().reverse().concat(element.nextSiblings()); + }, + + match: function(element, selector) { + if (typeof selector == 'string') + selector = new Selector(selector); + return selector.match($(element)); + }, + + up: function(element, expression, index) { + return Selector.findElement($(element).ancestors(), expression, index); + }, + + down: function(element, expression, index) { + return Selector.findElement($(element).descendants(), expression, index); + }, + + previous: function(element, expression, index) { + return Selector.findElement($(element).previousSiblings(), expression, index); + }, + + next: function(element, expression, index) { + return Selector.findElement($(element).nextSiblings(), expression, index); + }, + + getElementsBySelector: function() { + var args = $A(arguments), element = $(args.shift()); + return Selector.findChildElements(element, args); + }, + + getElementsByClassName: function(element, className) { + return document.getElementsByClassName(className, element); + }, + + readAttribute: function(element, name) { + element = $(element); + if (document.all && !window.opera) { + var t = Element._attributeTranslations; + if (t.values[name]) return t.values[name](element, name); + if (t.names[name]) name = t.names[name]; + var attribute = element.attributes[name]; + if(attribute) return attribute.nodeValue; + } + return element.getAttribute(name); + }, + + getHeight: function(element) { + return $(element).getDimensions().height; + }, + + getWidth: function(element) { + return $(element).getDimensions().width; + }, + + classNames: function(element) { + return new Element.ClassNames(element); + }, + + hasClassName: function(element, className) { + if (!(element = $(element))) return; + var elementClassName = element.className; + if (elementClassName.length == 0) return false; + if (elementClassName == className || + elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) + return true; + return false; + }, + + addClassName: function(element, className) { + if (!(element = $(element))) return; + Element.classNames(element).add(className); + return element; + }, + + removeClassName: function(element, className) { + if (!(element = $(element))) return; + Element.classNames(element).remove(className); + return element; + }, + + toggleClassName: function(element, className) { + if (!(element = $(element))) return; + Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className); + return element; + }, + + observe: function() { + Event.observe.apply(Event, arguments); + return $A(arguments).first(); + }, + + stopObserving: function() { + Event.stopObserving.apply(Event, arguments); + return $A(arguments).first(); + }, + + // removes whitespace-only text node children + cleanWhitespace: function(element) { + element = $(element); + var node = element.firstChild; + while (node) { + var nextNode = node.nextSibling; + if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) + element.removeChild(node); + node = nextNode; + } + return element; + }, + + empty: function(element) { + return $(element).innerHTML.match(/^\s*$/); + }, + + descendantOf: function(element, ancestor) { + element = $(element), ancestor = $(ancestor); + while (element = element.parentNode) + if (element == ancestor) return true; + return false; + }, + + scrollTo: function(element) { + element = $(element); + var pos = Position.cumulativeOffset(element); + window.scrollTo(pos[0], pos[1]); + return element; + }, + + getStyle: function(element, style) { + element = $(element); + if (['float','cssFloat'].include(style)) + style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat'); + style = style.camelize(); + var value = element.style[style]; + if (!value) { + if (document.defaultView && document.defaultView.getComputedStyle) { + var css = document.defaultView.getComputedStyle(element, null); + value = css ? css[style] : null; + } else if (element.currentStyle) { + value = element.currentStyle[style]; + } + } + + if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none')) + value = element['offset'+style.capitalize()] + 'px'; + + if (window.opera && ['left', 'top', 'right', 'bottom'].include(style)) + if (Element.getStyle(element, 'position') == 'static') value = 'auto'; + if(style == 'opacity') { + if(value) return parseFloat(value); + if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) + if(value[1]) return parseFloat(value[1]) / 100; + return 1.0; + } + return value == 'auto' ? null : value; + }, + + setStyle: function(element, style) { + element = $(element); + for (var name in style) { + var value = style[name]; + if(name == 'opacity') { + if (value == 1) { + value = (/Gecko/.test(navigator.userAgent) && + !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0; + if(/MSIE/.test(navigator.userAgent) && !window.opera) + element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,''); + } else if(value == '') { + if(/MSIE/.test(navigator.userAgent) && !window.opera) + element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,''); + } else { + if(value < 0.00001) value = 0; + if(/MSIE/.test(navigator.userAgent) && !window.opera) + element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') + + 'alpha(opacity='+value*100+')'; + } + } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat'; + element.style[name.camelize()] = value; + } + return element; + }, + + getDimensions: function(element) { + element = $(element); + var display = $(element).getStyle('display'); + if (display != 'none' && display != null) // Safari bug + return {width: element.offsetWidth, height: element.offsetHeight}; + + // All *Width and *Height properties give 0 on elements with display none, + // so enable the element temporarily + var els = element.style; + var originalVisibility = els.visibility; + var originalPosition = els.position; + var originalDisplay = els.display; + els.visibility = 'hidden'; + els.position = 'absolute'; + els.display = 'block'; + var originalWidth = element.clientWidth; + var originalHeight = element.clientHeight; + els.display = originalDisplay; + els.position = originalPosition; + els.visibility = originalVisibility; + return {width: originalWidth, height: originalHeight}; + }, + + makePositioned: function(element) { + element = $(element); + var pos = Element.getStyle(element, 'position'); + if (pos == 'static' || !pos) { + element._madePositioned = true; + element.style.position = 'relative'; + // Opera returns the offset relative to the positioning context, when an + // element is position relative but top and left have not been defined + if (window.opera) { + element.style.top = 0; + element.style.left = 0; + } + } + return element; + }, + + undoPositioned: function(element) { + element = $(element); + if (element._madePositioned) { + element._madePositioned = undefined; + element.style.position = + element.style.top = + element.style.left = + element.style.bottom = + element.style.right = ''; + } + return element; + }, + + makeClipping: function(element) { + element = $(element); + if (element._overflow) return element; + element._overflow = element.style.overflow || 'auto'; + if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden') + element.style.overflow = 'hidden'; + return element; + }, + + undoClipping: function(element) { + element = $(element); + if (!element._overflow) return element; + element.style.overflow = element._overflow == 'auto' ? '' : element._overflow; + element._overflow = null; + return element; + } +}; + +Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf}); + +Element._attributeTranslations = {}; + +Element._attributeTranslations.names = { + colspan: "colSpan", + rowspan: "rowSpan", + valign: "vAlign", + datetime: "dateTime", + accesskey: "accessKey", + tabindex: "tabIndex", + enctype: "encType", + maxlength: "maxLength", + readonly: "readOnly", + longdesc: "longDesc" +}; + +Element._attributeTranslations.values = { + _getAttr: function(element, attribute) { + return element.getAttribute(attribute, 2); + }, + + _flag: function(element, attribute) { + return $(element).hasAttribute(attribute) ? attribute : null; + }, + + style: function(element) { + return element.style.cssText.toLowerCase(); + }, + + title: function(element) { + var node = element.getAttributeNode('title'); + return node.specified ? node.nodeValue : null; + } +}; + +Object.extend(Element._attributeTranslations.values, { + href: Element._attributeTranslations.values._getAttr, + src: Element._attributeTranslations.values._getAttr, + disabled: Element._attributeTranslations.values._flag, + checked: Element._attributeTranslations.values._flag, + readonly: Element._attributeTranslations.values._flag, + multiple: Element._attributeTranslations.values._flag +}); + +Element.Methods.Simulated = { + hasAttribute: function(element, attribute) { + var t = Element._attributeTranslations; + attribute = t.names[attribute] || attribute; + return $(element).getAttributeNode(attribute).specified; + } +}; + +// IE is missing .innerHTML support for TABLE-related elements +if (document.all && !window.opera){ + Element.Methods.update = function(element, html) { + element = $(element); + html = typeof html == 'undefined' ? '' : html.toString(); + var tagName = element.tagName.toUpperCase(); + if (['THEAD','TBODY','TR','TD'].include(tagName)) { + var div = document.createElement('div'); + switch (tagName) { + case 'THEAD': + case 'TBODY': + div.innerHTML = '' + html.stripScripts() + '
    '; + depth = 2; + break; + case 'TR': + div.innerHTML = '' + html.stripScripts() + '
    '; + depth = 3; + break; + case 'TD': + div.innerHTML = '
    ' + html.stripScripts() + '
    '; + depth = 4; + } + $A(element.childNodes).each(function(node){ + element.removeChild(node) + }); + depth.times(function(){ div = div.firstChild }); + + $A(div.childNodes).each( + function(node){ element.appendChild(node) }); + } else { + element.innerHTML = html.stripScripts(); + } + setTimeout(function() {html.evalScripts()}, 10); + return element; + } +}; + +Object.extend(Element, Element.Methods); + +var _nativeExtensions = false; + +if(/Konqueror|Safari|KHTML/.test(navigator.userAgent)) + ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) { + var className = 'HTML' + tag + 'Element'; + if(window[className]) return; + var klass = window[className] = {}; + klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__; + }); + +Element.addMethods = function(methods) { + Object.extend(Element.Methods, methods || {}); + + function copy(methods, destination, onlyIfAbsent) { + onlyIfAbsent = onlyIfAbsent || false; + var cache = Element.extend.cache; + for (var property in methods) { + var value = methods[property]; + if (!onlyIfAbsent || !(property in destination)) + destination[property] = cache.findOrStore(value); + } + } + + if (typeof HTMLElement != 'undefined') { + copy(Element.Methods, HTMLElement.prototype); + copy(Element.Methods.Simulated, HTMLElement.prototype, true); + copy(Form.Methods, HTMLFormElement.prototype); + [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) { + copy(Form.Element.Methods, klass.prototype); + }); + _nativeExtensions = true; + } +} + +var Toggle = new Object(); +Toggle.display = Element.toggle; + +/*--------------------------------------------------------------------------*/ + +Abstract.Insertion = function(adjacency) { + this.adjacency = adjacency; +} + +Abstract.Insertion.prototype = { + initialize: function(element, content) { + this.element = $(element); + this.content = content.stripScripts(); + + if (this.adjacency && this.element.insertAdjacentHTML) { + try { + this.element.insertAdjacentHTML(this.adjacency, this.content); + } catch (e) { + var tagName = this.element.tagName.toUpperCase(); + if (['TBODY', 'TR'].include(tagName)) { + this.insertContent(this.contentFromAnonymousTable()); + } else { + throw e; + } + } + } else { + this.range = this.element.ownerDocument.createRange(); + if (this.initializeRange) this.initializeRange(); + this.insertContent([this.range.createContextualFragment(this.content)]); + } + + setTimeout(function() {content.evalScripts()}, 10); + }, + + contentFromAnonymousTable: function() { + var div = document.createElement('div'); + div.innerHTML = '' + this.content + '
    '; + return $A(div.childNodes[0].childNodes[0].childNodes); + } +} + +var Insertion = new Object(); + +Insertion.Before = Class.create(); +Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), { + initializeRange: function() { + this.range.setStartBefore(this.element); + }, + + insertContent: function(fragments) { + fragments.each((function(fragment) { + this.element.parentNode.insertBefore(fragment, this.element); + }).bind(this)); + } +}); + +Insertion.Top = Class.create(); +Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), { + initializeRange: function() { + this.range.selectNodeContents(this.element); + this.range.collapse(true); + }, + + insertContent: function(fragments) { + fragments.reverse(false).each((function(fragment) { + this.element.insertBefore(fragment, this.element.firstChild); + }).bind(this)); + } +}); + +Insertion.Bottom = Class.create(); +Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), { + initializeRange: function() { + this.range.selectNodeContents(this.element); + this.range.collapse(this.element); + }, + + insertContent: function(fragments) { + fragments.each((function(fragment) { + this.element.appendChild(fragment); + }).bind(this)); + } +}); + +Insertion.After = Class.create(); +Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), { + initializeRange: function() { + this.range.setStartAfter(this.element); + }, + + insertContent: function(fragments) { + fragments.each((function(fragment) { + this.element.parentNode.insertBefore(fragment, + this.element.nextSibling); + }).bind(this)); + } +}); + +/*--------------------------------------------------------------------------*/ + +Element.ClassNames = Class.create(); +Element.ClassNames.prototype = { + initialize: function(element) { + this.element = $(element); + }, + + _each: function(iterator) { + this.element.className.split(/\s+/).select(function(name) { + return name.length > 0; + })._each(iterator); + }, + + set: function(className) { + this.element.className = className; + }, + + add: function(classNameToAdd) { + if (this.include(classNameToAdd)) return; + this.set($A(this).concat(classNameToAdd).join(' ')); + }, + + remove: function(classNameToRemove) { + if (!this.include(classNameToRemove)) return; + this.set($A(this).without(classNameToRemove).join(' ')); + }, + + toString: function() { + return $A(this).join(' '); + } +}; + +Object.extend(Element.ClassNames.prototype, Enumerable); +var Selector = Class.create(); +Selector.prototype = { + initialize: function(expression) { + this.params = {classNames: []}; + this.expression = expression.toString().strip(); + this.parseExpression(); + this.compileMatcher(); + }, + + parseExpression: function() { + function abort(message) { throw 'Parse error in selector: ' + message; } + + if (this.expression == '') abort('empty expression'); + + var params = this.params, expr = this.expression, match, modifier, clause, rest; + while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) { + params.attributes = params.attributes || []; + params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''}); + expr = match[1]; + } + + if (expr == '*') return this.params.wildcard = true; + + while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) { + modifier = match[1], clause = match[2], rest = match[3]; + switch (modifier) { + case '#': params.id = clause; break; + case '.': params.classNames.push(clause); break; + case '': + case undefined: params.tagName = clause.toUpperCase(); break; + default: abort(expr.inspect()); + } + expr = rest; + } + + if (expr.length > 0) abort(expr.inspect()); + }, + + buildMatchExpression: function() { + var params = this.params, conditions = [], clause; + + if (params.wildcard) + conditions.push('true'); + if (clause = params.id) + conditions.push('element.readAttribute("id") == ' + clause.inspect()); + if (clause = params.tagName) + conditions.push('element.tagName.toUpperCase() == ' + clause.inspect()); + if ((clause = params.classNames).length > 0) + for (var i = 0, length = clause.length; i < length; i++) + conditions.push('element.hasClassName(' + clause[i].inspect() + ')'); + if (clause = params.attributes) { + clause.each(function(attribute) { + var value = 'element.readAttribute(' + attribute.name.inspect() + ')'; + var splitValueBy = function(delimiter) { + return value + ' && ' + value + '.split(' + delimiter.inspect() + ')'; + } + + switch (attribute.operator) { + case '=': conditions.push(value + ' == ' + attribute.value.inspect()); break; + case '~=': conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break; + case '|=': conditions.push( + splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect() + ); break; + case '!=': conditions.push(value + ' != ' + attribute.value.inspect()); break; + case '': + case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break; + default: throw 'Unknown operator ' + attribute.operator + ' in selector'; + } + }); + } + + return conditions.join(' && '); + }, + + compileMatcher: function() { + this.match = new Function('element', 'if (!element.tagName) return false; \ + element = $(element); \ + return ' + this.buildMatchExpression()); + }, + + findElements: function(scope) { + var element; + + if (element = $(this.params.id)) + if (this.match(element)) + if (!scope || Element.childOf(element, scope)) + return [element]; + + scope = (scope || document).getElementsByTagName(this.params.tagName || '*'); + + var results = []; + for (var i = 0, length = scope.length; i < length; i++) + if (this.match(element = scope[i])) + results.push(Element.extend(element)); + + return results; + }, + + toString: function() { + return this.expression; + } +} + +Object.extend(Selector, { + matchElements: function(elements, expression) { + var selector = new Selector(expression); + return elements.select(selector.match.bind(selector)).map(Element.extend); + }, + + findElement: function(elements, expression, index) { + if (typeof expression == 'number') index = expression, expression = false; + return Selector.matchElements(elements, expression || '*')[index || 0]; + }, + + findChildElements: function(element, expressions) { + return expressions.map(function(expression) { + return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) { + var selector = new Selector(expr); + return results.inject([], function(elements, result) { + return elements.concat(selector.findElements(result || element)); + }); + }); + }).flatten(); + } +}); + +function $$() { + return Selector.findChildElements(document, $A(arguments)); +} +var Form = { + reset: function(form) { + $(form).reset(); + return form; + }, + + serializeElements: function(elements, getHash) { + var data = elements.inject({}, function(result, element) { + if (!element.disabled && element.name) { + var key = element.name, value = $(element).getValue(); + if (value != undefined) { + if (result[key]) { + if (result[key].constructor != Array) result[key] = [result[key]]; + result[key].push(value); + } + else result[key] = value; + } + } + return result; + }); + + return getHash ? data : Hash.toQueryString(data); + } +}; + +Form.Methods = { + serialize: function(form, getHash) { + return Form.serializeElements(Form.getElements(form), getHash); + }, + + getElements: function(form) { + return $A($(form).getElementsByTagName('*')).inject([], + function(elements, child) { + if (Form.Element.Serializers[child.tagName.toLowerCase()]) + elements.push(Element.extend(child)); + return elements; + } + ); + }, + + getInputs: function(form, typeName, name) { + form = $(form); + var inputs = form.getElementsByTagName('input'); + + if (!typeName && !name) return $A(inputs).map(Element.extend); + + for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { + var input = inputs[i]; + if ((typeName && input.type != typeName) || (name && input.name != name)) + continue; + matchingInputs.push(Element.extend(input)); + } + + return matchingInputs; + }, + + disable: function(form) { + form = $(form); + form.getElements().each(function(element) { + element.blur(); + element.disabled = 'true'; + }); + return form; + }, + + enable: function(form) { + form = $(form); + form.getElements().each(function(element) { + element.disabled = ''; + }); + return form; + }, + + findFirstElement: function(form) { + return $(form).getElements().find(function(element) { + return element.type != 'hidden' && !element.disabled && + ['input', 'select', 'textarea'].include(element.tagName.toLowerCase()); + }); + }, + + focusFirstElement: function(form) { + form = $(form); + form.findFirstElement().activate(); + return form; + } +} + +Object.extend(Form, Form.Methods); + +/*--------------------------------------------------------------------------*/ + +Form.Element = { + focus: function(element) { + $(element).focus(); + return element; + }, + + select: function(element) { + $(element).select(); + return element; + } +} + +Form.Element.Methods = { + serialize: function(element) { + element = $(element); + if (!element.disabled && element.name) { + var value = element.getValue(); + if (value != undefined) { + var pair = {}; + pair[element.name] = value; + return Hash.toQueryString(pair); + } + } + return ''; + }, + + getValue: function(element) { + element = $(element); + var method = element.tagName.toLowerCase(); + return Form.Element.Serializers[method](element); + }, + + clear: function(element) { + $(element).value = ''; + return element; + }, + + present: function(element) { + return $(element).value != ''; + }, + + activate: function(element) { + element = $(element); + element.focus(); + if (element.select && ( element.tagName.toLowerCase() != 'input' || + !['button', 'reset', 'submit'].include(element.type) ) ) + element.select(); + return element; + }, + + disable: function(element) { + element = $(element); + element.disabled = true; + return element; + }, + + enable: function(element) { + element = $(element); + element.blur(); + element.disabled = false; + return element; + } +} + +Object.extend(Form.Element, Form.Element.Methods); +var Field = Form.Element; +var $F = Form.Element.getValue; + +/*--------------------------------------------------------------------------*/ + +Form.Element.Serializers = { + input: function(element) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + return Form.Element.Serializers.inputSelector(element); + default: + return Form.Element.Serializers.textarea(element); + } + }, + + inputSelector: function(element) { + return element.checked ? element.value : null; + }, + + textarea: function(element) { + return element.value; + }, + + select: function(element) { + return this[element.type == 'select-one' ? + 'selectOne' : 'selectMany'](element); + }, + + selectOne: function(element) { + var index = element.selectedIndex; + return index >= 0 ? this.optionValue(element.options[index]) : null; + }, + + selectMany: function(element) { + var values, length = element.length; + if (!length) return null; + + for (var i = 0, values = []; i < length; i++) { + var opt = element.options[i]; + if (opt.selected) values.push(this.optionValue(opt)); + } + return values; + }, + + optionValue: function(opt) { + // extend element because hasAttribute may not be native + return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; + } +} + +/*--------------------------------------------------------------------------*/ + +Abstract.TimedObserver = function() {} +Abstract.TimedObserver.prototype = { + initialize: function(element, frequency, callback) { + this.frequency = frequency; + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + this.registerCallback(); + }, + + registerCallback: function() { + setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + onTimerEvent: function() { + var value = this.getValue(); + var changed = ('string' == typeof this.lastValue && 'string' == typeof value + ? this.lastValue != value : String(this.lastValue) != String(value)); + if (changed) { + this.callback(this.element, value); + this.lastValue = value; + } + } +} + +Form.Element.Observer = Class.create(); +Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.Observer = Class.create(); +Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { + getValue: function() { + return Form.serialize(this.element); + } +}); + +/*--------------------------------------------------------------------------*/ + +Abstract.EventObserver = function() {} +Abstract.EventObserver.prototype = { + initialize: function(element, callback) { + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + if (this.element.tagName.toLowerCase() == 'form') + this.registerFormCallbacks(); + else + this.registerCallback(this.element); + }, + + onElementEvent: function() { + var value = this.getValue(); + if (this.lastValue != value) { + this.callback(this.element, value); + this.lastValue = value; + } + }, + + registerFormCallbacks: function() { + Form.getElements(this.element).each(this.registerCallback.bind(this)); + }, + + registerCallback: function(element) { + if (element.type) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + Event.observe(element, 'click', this.onElementEvent.bind(this)); + break; + default: + Event.observe(element, 'change', this.onElementEvent.bind(this)); + break; + } + } + } +} + +Form.Element.EventObserver = Class.create(); +Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.EventObserver = Class.create(); +Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { + getValue: function() { + return Form.serialize(this.element); + } +}); +if (!window.Event) { + var Event = new Object(); +} + +Object.extend(Event, { + KEY_BACKSPACE: 8, + KEY_TAB: 9, + KEY_RETURN: 13, + KEY_ESC: 27, + KEY_LEFT: 37, + KEY_UP: 38, + KEY_RIGHT: 39, + KEY_DOWN: 40, + KEY_DELETE: 46, + KEY_HOME: 36, + KEY_END: 35, + KEY_PAGEUP: 33, + KEY_PAGEDOWN: 34, + + element: function(event) { + return event.target || event.srcElement; + }, + + isLeftClick: function(event) { + return (((event.which) && (event.which == 1)) || + ((event.button) && (event.button == 1))); + }, + + pointerX: function(event) { + return event.pageX || (event.clientX + + (document.documentElement.scrollLeft || document.body.scrollLeft)); + }, + + pointerY: function(event) { + return event.pageY || (event.clientY + + (document.documentElement.scrollTop || document.body.scrollTop)); + }, + + stop: function(event) { + if (event.preventDefault) { + event.preventDefault(); + event.stopPropagation(); + } else { + event.returnValue = false; + event.cancelBubble = true; + } + }, + + // find the first node with the given tagName, starting from the + // node the event was triggered on; traverses the DOM upwards + findElement: function(event, tagName) { + var element = Event.element(event); + while (element.parentNode && (!element.tagName || + (element.tagName.toUpperCase() != tagName.toUpperCase()))) + element = element.parentNode; + return element; + }, + + observers: false, + + _observeAndCache: function(element, name, observer, useCapture) { + if (!this.observers) this.observers = []; + if (element.addEventListener) { + this.observers.push([element, name, observer, useCapture]); + element.addEventListener(name, observer, useCapture); + } else if (element.attachEvent) { + this.observers.push([element, name, observer, useCapture]); + element.attachEvent('on' + name, observer); + } + }, + + unloadCache: function() { + if (!Event.observers) return; + for (var i = 0, length = Event.observers.length; i < length; i++) { + Event.stopObserving.apply(this, Event.observers[i]); + Event.observers[i][0] = null; + } + Event.observers = false; + }, + + observe: function(element, name, observer, useCapture) { + element = $(element); + useCapture = useCapture || false; + + if (name == 'keypress' && + (navigator.appVersion.match(/Konqueror|Safari|KHTML/) + || element.attachEvent)) + name = 'keydown'; + + Event._observeAndCache(element, name, observer, useCapture); + }, + + stopObserving: function(element, name, observer, useCapture) { + element = $(element); + useCapture = useCapture || false; + + if (name == 'keypress' && + (navigator.appVersion.match(/Konqueror|Safari|KHTML/) + || element.detachEvent)) + name = 'keydown'; + + if (element.removeEventListener) { + element.removeEventListener(name, observer, useCapture); + } else if (element.detachEvent) { + try { + element.detachEvent('on' + name, observer); + } catch (e) {} + } + } +}); + +/* prevent memory leaks in IE */ +if (navigator.appVersion.match(/\bMSIE\b/)) + Event.observe(window, 'unload', Event.unloadCache, false); +var Position = { + // set to true if needed, warning: firefox performance problems + // NOT neeeded for page scrolling, only if draggable contained in + // scrollable elements + includeScrollOffsets: false, + + // must be called before calling withinIncludingScrolloffset, every time the + // page is scrolled + prepare: function() { + this.deltaX = window.pageXOffset + || document.documentElement.scrollLeft + || document.body.scrollLeft + || 0; + this.deltaY = window.pageYOffset + || document.documentElement.scrollTop + || document.body.scrollTop + || 0; + }, + + realOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.scrollTop || 0; + valueL += element.scrollLeft || 0; + element = element.parentNode; + } while (element); + return [valueL, valueT]; + }, + + cumulativeOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + return [valueL, valueT]; + }, + + positionedOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + if (element) { + if(element.tagName=='BODY') break; + var p = Element.getStyle(element, 'position'); + if (p == 'relative' || p == 'absolute') break; + } + } while (element); + return [valueL, valueT]; + }, + + offsetParent: function(element) { + if (element.offsetParent) return element.offsetParent; + if (element == document.body) return element; + + while ((element = element.parentNode) && element != document.body) + if (Element.getStyle(element, 'position') != 'static') + return element; + + return document.body; + }, + + // caches x/y coordinate pair to use with overlap + within: function(element, x, y) { + if (this.includeScrollOffsets) + return this.withinIncludingScrolloffsets(element, x, y); + this.xcomp = x; + this.ycomp = y; + this.offset = this.cumulativeOffset(element); + + return (y >= this.offset[1] && + y < this.offset[1] + element.offsetHeight && + x >= this.offset[0] && + x < this.offset[0] + element.offsetWidth); + }, + + withinIncludingScrolloffsets: function(element, x, y) { + var offsetcache = this.realOffset(element); + + this.xcomp = x + offsetcache[0] - this.deltaX; + this.ycomp = y + offsetcache[1] - this.deltaY; + this.offset = this.cumulativeOffset(element); + + return (this.ycomp >= this.offset[1] && + this.ycomp < this.offset[1] + element.offsetHeight && + this.xcomp >= this.offset[0] && + this.xcomp < this.offset[0] + element.offsetWidth); + }, + + // within must be called directly before + overlap: function(mode, element) { + if (!mode) return 0; + if (mode == 'vertical') + return ((this.offset[1] + element.offsetHeight) - this.ycomp) / + element.offsetHeight; + if (mode == 'horizontal') + return ((this.offset[0] + element.offsetWidth) - this.xcomp) / + element.offsetWidth; + }, + + page: function(forElement) { + var valueT = 0, valueL = 0; + + var element = forElement; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + + // Safari fix + if (element.offsetParent==document.body) + if (Element.getStyle(element,'position')=='absolute') break; + + } while (element = element.offsetParent); + + element = forElement; + do { + if (!window.opera || element.tagName=='BODY') { + valueT -= element.scrollTop || 0; + valueL -= element.scrollLeft || 0; + } + } while (element = element.parentNode); + + return [valueL, valueT]; + }, + + clone: function(source, target) { + var options = Object.extend({ + setLeft: true, + setTop: true, + setWidth: true, + setHeight: true, + offsetTop: 0, + offsetLeft: 0 + }, arguments[2] || {}) + + // find page position of source + source = $(source); + var p = Position.page(source); + + // find coordinate system to use + target = $(target); + var delta = [0, 0]; + var parent = null; + // delta [0,0] will do fine with position: fixed elements, + // position:absolute needs offsetParent deltas + if (Element.getStyle(target,'position') == 'absolute') { + parent = Position.offsetParent(target); + delta = Position.page(parent); + } + + // correct by body offsets (fixes Safari) + if (parent == document.body) { + delta[0] -= document.body.offsetLeft; + delta[1] -= document.body.offsetTop; + } + + // set position + if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; + if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; + if(options.setWidth) target.style.width = source.offsetWidth + 'px'; + if(options.setHeight) target.style.height = source.offsetHeight + 'px'; + }, + + absolutize: function(element) { + element = $(element); + if (element.style.position == 'absolute') return; + Position.prepare(); + + var offsets = Position.positionedOffset(element); + var top = offsets[1]; + var left = offsets[0]; + var width = element.clientWidth; + var height = element.clientHeight; + + element._originalLeft = left - parseFloat(element.style.left || 0); + element._originalTop = top - parseFloat(element.style.top || 0); + element._originalWidth = element.style.width; + element._originalHeight = element.style.height; + + element.style.position = 'absolute'; + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.width = width + 'px'; + element.style.height = height + 'px'; + }, + + relativize: function(element) { + element = $(element); + if (element.style.position == 'relative') return; + Position.prepare(); + + element.style.position = 'relative'; + var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); + var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); + + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.height = element._originalHeight; + element.style.width = element._originalWidth; + } +} + +// Safari returns margins on body which is incorrect if the child is absolutely +// positioned. For performance reasons, redefine Position.cumulativeOffset for +// KHTML/WebKit only. +if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) { + Position.cumulativeOffset = function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == document.body) + if (Element.getStyle(element, 'position') == 'absolute') break; + + element = element.offsetParent; + } while (element); + + return [valueL, valueT]; + } +} + +Element.addMethods(); \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/robots.txt b/vendor/plugins/has_many_polymorphs/test/integration/app/public/robots.txt new file mode 100644 index 0000000..4ab9e89 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/robots.txt @@ -0,0 +1 @@ +# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/public/stylesheets/scaffold.css b/vendor/plugins/has_many_polymorphs/test/integration/app/public/stylesheets/scaffold.css new file mode 100644 index 0000000..8f239a3 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/public/stylesheets/scaffold.css @@ -0,0 +1,74 @@ +body { background-color: #fff; color: #333; } + +body, p, ol, ul, td { + font-family: verdana, arial, helvetica, sans-serif; + font-size: 13px; + line-height: 18px; +} + +pre { + background-color: #eee; + padding: 10px; + font-size: 11px; +} + +a { color: #000; } +a:visited { color: #666; } +a:hover { color: #fff; background-color:#000; } + +.fieldWithErrors { + padding: 2px; + background-color: red; + display: table; +} + +#errorExplanation { + width: 400px; + border: 2px solid red; + padding: 7px; + padding-bottom: 12px; + margin-bottom: 20px; + background-color: #f0f0f0; +} + +#errorExplanation h2 { + text-align: left; + font-weight: bold; + padding: 5px 5px 5px 15px; + font-size: 12px; + margin: -7px; + background-color: #c00; + color: #fff; +} + +#errorExplanation p { + color: #333; + margin-bottom: 0; + padding: 5px; +} + +#errorExplanation ul li { + font-size: 12px; + list-style: square; +} + +div.uploadStatus { + margin: 5px; +} + +div.progressBar { + margin: 5px; +} + +div.progressBar div.border { + background-color: #fff; + border: 1px solid grey; + width: 100%; +} + +div.progressBar div.background { + background-color: #333; + height: 18px; + width: 0%; +} + diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/about b/vendor/plugins/has_many_polymorphs/test/integration/app/script/about new file mode 100755 index 0000000..7b07d46 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/about @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/about' \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/breakpointer b/vendor/plugins/has_many_polymorphs/test/integration/app/script/breakpointer new file mode 100755 index 0000000..64af76e --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/breakpointer @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/breakpointer' \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/console b/vendor/plugins/has_many_polymorphs/test/integration/app/script/console new file mode 100755 index 0000000..42f28f7 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/console @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/console' \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/destroy b/vendor/plugins/has_many_polymorphs/test/integration/app/script/destroy new file mode 100755 index 0000000..fa0e6fc --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/destroy @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/destroy' \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/generate b/vendor/plugins/has_many_polymorphs/test/integration/app/script/generate new file mode 100755 index 0000000..ef976e0 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/generate @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/generate' \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/performance/benchmarker b/vendor/plugins/has_many_polymorphs/test/integration/app/script/performance/benchmarker new file mode 100755 index 0000000..c842d35 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/performance/benchmarker @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../config/boot' +require 'commands/performance/benchmarker' diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/performance/profiler b/vendor/plugins/has_many_polymorphs/test/integration/app/script/performance/profiler new file mode 100755 index 0000000..d855ac8 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/performance/profiler @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../config/boot' +require 'commands/performance/profiler' diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/plugin b/vendor/plugins/has_many_polymorphs/test/integration/app/script/plugin new file mode 100755 index 0000000..26ca64c --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/plugin @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/plugin' \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/process/inspector b/vendor/plugins/has_many_polymorphs/test/integration/app/script/process/inspector new file mode 100755 index 0000000..bf25ad8 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/process/inspector @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../config/boot' +require 'commands/process/inspector' diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/process/reaper b/vendor/plugins/has_many_polymorphs/test/integration/app/script/process/reaper new file mode 100755 index 0000000..c77f045 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/process/reaper @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../config/boot' +require 'commands/process/reaper' diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/process/spawner b/vendor/plugins/has_many_polymorphs/test/integration/app/script/process/spawner new file mode 100755 index 0000000..7118f39 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/process/spawner @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../config/boot' +require 'commands/process/spawner' diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/runner b/vendor/plugins/has_many_polymorphs/test/integration/app/script/runner new file mode 100755 index 0000000..ccc30f9 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/runner @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/runner' \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/script/server b/vendor/plugins/has_many_polymorphs/test/integration/app/script/server new file mode 100755 index 0000000..dfabcb8 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/script/server @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../config/boot' +require 'commands/server' \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/addresses.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/addresses.yml new file mode 100644 index 0000000..c92ba8d --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/addresses.yml @@ -0,0 +1,13 @@ +<% 1.upto(40) do |num| %> +<%="address#{num}:" %> + id: <%= num %> + user_id: <%= num %> + name: <%= "Chicago Branch Office #{num}" %> + line_1: "3344 Airport Road" + line_2: "Suite 122" + city: "Chicago" + state_id: 15 + province_region: "Cook County" + zip_postal_code: "43554" + country_id: 2 +<% end %> \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations.yml new file mode 100644 index 0000000..b2c68a7 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations.yml @@ -0,0 +1,9 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html +one: + id: 1 + created_at: 2007-10-04 17:14:07 + updated_at: 2007-10-04 17:14:07 +two: + id: 2 + created_at: 2007-10-04 17:14:07 + updated_at: 2007-10-04 17:14:07 diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations_items.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations_items.yml new file mode 100644 index 0000000..37bc5a1 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/citations_items.yml @@ -0,0 +1,9 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html +one: + id: 1 + created_at: 2007-10-04 17:14:27 + updated_at: 2007-10-04 17:14:27 +two: + id: 2 + created_at: 2007-10-04 17:14:27 + updated_at: 2007-10-04 17:14:27 diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/sellers.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/sellers.yml new file mode 100644 index 0000000..d056384 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/sellers.yml @@ -0,0 +1,10 @@ +<% 1.upto(20) do |num| %> +<%="seller#{num}:" %> + id: <%= num %> + user_id: <%= num %> + company_name: <%= "seller#{num}" %> + capitalization: <%= num * 1.548 %> + created_at: <%= (Time.now - num.weeks).to_s :db %> + updated_at: <%= (Time.now - num.days).to_s :db %> +<% end %> + diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/states.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/states.yml new file mode 100644 index 0000000..c2b1361 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/states.yml @@ -0,0 +1,216 @@ +AA:<% id = 0 %> + id: <%= (id=id+1).to_s %> + name: AA + abbreviation: AA +AE: + id: <%= (id=id+1).to_s %> + name: AE + abbreviation: AE +AP: + id: <%= (id=id+1).to_s %> + name: AP + abbreviation: AP +AL: + id: <%= (id=id+1).to_s %> + name: Alabama + abbreviation: AL +AK: + id: <%= (id=id+1).to_s %> + name: Alaska + abbreviation: AK +AZ: + id: <%= (id=id+1).to_s %> + name: Arizona + abbreviation: AZ +AR: + id: <%= (id=id+1).to_s %> + name: Arkansas + abbreviation: AR +CA: + id: <%= (id=id+1).to_s %> + name: California + abbreviation: CA +CO: + id: <%= (id=id+1).to_s %> + name: Colorado + abbreviation: CO +CT: + id: <%= (id=id+1).to_s %> + name: Connecticut + abbreviation: CT +DE: + id: <%= (id=id+1).to_s %> + name: Delaware + abbreviation: DE +DC: + id: <%= (id=id+1).to_s %> + name: District of Columbia + abbreviation: DC +FL: + id: <%= (id=id+1).to_s %> + name: Florida + abbreviation: FL +GA: + id: <%= (id=id+1).to_s %> + name: Georgia + abbreviation: GA +HI: + id: <%= (id=id+1).to_s %> + name: Hawaii + abbreviation: HI +ID: + id: <%= (id=id+1).to_s %> + name: Idaho + abbreviation: ID +IL: + id: <%= (id=id+1).to_s %> + name: Illinois + abbreviation: IL +IN: + id: <%= (id=id+1).to_s %> + name: Indiana + abbreviation: IN +IA: + id: <%= (id=id+1).to_s %> + name: Iowa + abbreviation: IA +KS: + id: <%= (id=id+1).to_s %> + name: Kansas + abbreviation: KS +KY: + id: <%= (id=id+1).to_s %> + name: Kentucky + abbreviation: KY +LA: + id: <%= (id=id+1).to_s %> + name: Louisiana + abbreviation: LA +ME: + id: <%= (id=id+1).to_s %> + name: Maine + abbreviation: ME +MD: + id: <%= (id=id+1).to_s %> + name: Maryland + abbreviation: MD +MA: + id: <%= (id=id+1).to_s %> + name: Massachusetts + abbreviation: MA +MI: + id: <%= (id=id+1).to_s %> + name: Michigan + abbreviation: MI +MN: + id: <%= (id=id+1).to_s %> + name: Minnesota + abbreviation: MN +MS: + id: <%= (id=id+1).to_s %> + name: Mississippi + abbreviation: MS +MO: + id: <%= (id=id+1).to_s %> + name: Missouri + abbreviation: MO +MT: + id: <%= (id=id+1).to_s %> + name: Montana + abbreviation: MT +NE: + id: <%= (id=id+1).to_s %> + name: Nebraska + abbreviation: NE +NV: + id: <%= (id=id+1).to_s %> + name: Nevada + abbreviation: NV +NH: + id: <%= (id=id+1).to_s %> + name: New Hampshire + abbreviation: NH +NJ: + id: <%= (id=id+1).to_s %> + name: New Jersey + abbreviation: NJ +NM: + id: <%= (id=id+1).to_s %> + name: New Mexico + abbreviation: NM +NY: + id: <%= (id=id+1).to_s %> + name: New York + abbreviation: NY +NC: + id: <%= (id=id+1).to_s %> + name: North Carolina + abbreviation: NC +ND: + id: <%= (id=id+1).to_s %> + name: North Dakota + abbreviation: ND +OH: + id: <%= (id=id+1).to_s %> + name: Ohio + abbreviation: OH +OK: + id: <%= (id=id+1).to_s %> + name: Oklahoma + abbreviation: OK +OR: + id: <%= (id=id+1).to_s %> + name: Oregon + abbreviation: OR +PA: + id: <%= (id=id+1).to_s %> + name: Pennsylvania + abbreviation: PA +RI: + id: <%= (id=id+1).to_s %> + name: Rhode Island + abbreviation: RI +SC: + id: <%= (id=id+1).to_s %> + name: South Carolina + abbreviation: SC +SD: + id: <%= (id=id+1).to_s %> + name: South Dakota + abbreviation: SD +TN: + id: <%= (id=id+1).to_s %> + name: Tennessee + abbreviation: TN +TX: + id: <%= (id=id+1).to_s %> + name: Texas + abbreviation: TX +UT: + id: <%= (id=id+1).to_s %> + name: Utah + abbreviation: UT +VT: + id: <%= (id=id+1).to_s %> + name: Vermont + abbreviation: VT +VA: + id: <%= (id=id+1).to_s %> + name: Virginia + abbreviation: VA +WA: + id: <%= (id=id+1).to_s %> + name: Washington + abbreviation: WA +WV: + id: <%= (id=id+1).to_s %> + name: West Virginia + abbreviation: WV +WI: + id: <%= (id=id+1).to_s %> + name: Wisconsin + abbreviation: WI +WY: + id: <%= (id=id+1).to_s %> + name: Wyoming + abbreviation: WY \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/users.yml b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/users.yml new file mode 100644 index 0000000..36c366f --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/fixtures/users.yml @@ -0,0 +1,11 @@ +<% 1.upto(41) do |num| %> +<%="user#{num}:" %> + id: <%= num.to_s %> + login: <%= "user#{num}" %> + crypted_password: "2fdefe5c83d80a03a828dd65e90cfff65f0fb42d043a254ca2cad6af968d0e15" #password + email: <%= "user#{num}@test.com" %> + salt: "1000" + created_at: <%= (Time.now - 30).to_s :db %> + updated_at: <%= Time.now.to_s :db %> + deleted: <%= num == 41 ? true : false %> +<% end %> diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/addresses_controller_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/addresses_controller_test.rb new file mode 100644 index 0000000..65284b5 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/addresses_controller_test.rb @@ -0,0 +1,57 @@ +require File.dirname(__FILE__) + '/../test_helper' +require 'addresses_controller' + +# Re-raise errors caught by the controller. +class AddressesController; def rescue_action(e) raise e end; end + +class AddressesControllerTest < Test::Unit::TestCase + fixtures :addresses + + def setup + @controller = AddressesController.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + end + + def test_should_get_index + get :index + assert_response :success + assert assigns(:addresses) + end + + def test_should_get_new + get :new + assert_response :success + end + + def test_should_create_address + assert_difference('Address.count') do + post :create, :address => { :country_id => 1, :user_id => 1, :state_id => 1} + end + + assert_redirected_to address_path(assigns(:address)) + end + + def test_should_show_address + get :show, :id => 1 + assert_response :success + end + + def test_should_get_edit + get :edit, :id => 1 + assert_response :success + end + + def test_should_update_address + put :update, :id => 1, :address => { } + assert_redirected_to address_path(assigns(:address)) + end + + def test_should_destroy_address + assert_difference('Address.count', -1) do + delete :destroy, :id => 1 + end + + assert_redirected_to addresses_path + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/sellers_controller_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/sellers_controller_test.rb new file mode 100644 index 0000000..fb992e5 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/sellers_controller_test.rb @@ -0,0 +1,57 @@ +require File.dirname(__FILE__) + '/../test_helper' +require 'sellers_controller' + +# Re-raise errors caught by the controller. +class SellersController; def rescue_action(e) raise e end; end + +class SellersControllerTest < Test::Unit::TestCase + fixtures :sellers + + def setup + @controller = SellersController.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + end + + def test_should_get_index + get :index + assert_response :success + assert assigns(:sellers) + end + + def test_should_get_new + get :new + assert_response :success + end + + def test_should_create_seller + assert_difference('Seller.count') do + post :create, :seller => { } + end + + assert_redirected_to seller_path(assigns(:seller)) + end + + def test_should_show_seller + get :show, :id => 1 + assert_response :success + end + + def test_should_get_edit + get :edit, :id => 1 + assert_response :success + end + + def test_should_update_seller + put :update, :id => 1, :seller => { } + assert_redirected_to seller_path(assigns(:seller)) + end + + def test_should_destroy_seller + assert_difference('Seller.count', -1) do + delete :destroy, :id => 1 + end + + assert_redirected_to sellers_path + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/states_controller_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/states_controller_test.rb new file mode 100644 index 0000000..2e93453 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/states_controller_test.rb @@ -0,0 +1,57 @@ +require File.dirname(__FILE__) + '/../test_helper' +require 'states_controller' + +# Re-raise errors caught by the controller. +class StatesController; def rescue_action(e) raise e end; end + +class StatesControllerTest < Test::Unit::TestCase + fixtures :states + + def setup + @controller = StatesController.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + end + + def test_should_get_index + get :index + assert_response :success + assert assigns(:states) + end + + def test_should_get_new + get :new + assert_response :success + end + + def test_should_create_state + assert_difference('State.count') do + post :create, :state => { } + end + + assert_redirected_to state_path(assigns(:state)) + end + + def test_should_show_state + get :show, :id => 1 + assert_response :success + end + + def test_should_get_edit + get :edit, :id => 1 + assert_response :success + end + + def test_should_update_state + put :update, :id => 1, :state => { } + assert_redirected_to state_path(assigns(:state)) + end + + def test_should_destroy_state + assert_difference('State.count', -1) do + delete :destroy, :id => 1 + end + + assert_redirected_to states_path + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/users_controller_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/users_controller_test.rb new file mode 100644 index 0000000..bc36751 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/functional/users_controller_test.rb @@ -0,0 +1,57 @@ +require File.dirname(__FILE__) + '/../test_helper' +require 'users_controller' + +# Re-raise errors caught by the controller. +class UsersController; def rescue_action(e) raise e end; end + +class UsersControllerTest < Test::Unit::TestCase + fixtures :users + + def setup + @controller = UsersController.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + end + + def test_should_get_index + get :index + assert_response :success + assert assigns(:users) + end + + def test_should_get_new + get :new + assert_response :success + end + + def test_should_create_user + assert_difference('User.count') do + post :create, :user => { } + end + + assert_redirected_to user_path(assigns(:user)) + end + + def test_should_show_user + get :show, :id => 1 + assert_response :success + end + + def test_should_get_edit + get :edit, :id => 1 + assert_response :success + end + + def test_should_update_user + put :update, :id => 1, :user => { } + assert_redirected_to user_path(assigns(:user)) + end + + def test_should_destroy_user + assert_difference('User.count', -1) do + delete :destroy, :id => 1 + end + + assert_redirected_to users_path + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/test_helper.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/test_helper.rb new file mode 100644 index 0000000..a299c7f --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/test_helper.rb @@ -0,0 +1,28 @@ +ENV["RAILS_ENV"] = "test" +require File.expand_path(File.dirname(__FILE__) + "/../config/environment") +require 'test_help' + +class Test::Unit::TestCase + # Transactional fixtures accelerate your tests by wrapping each test method + # in a transaction that's rolled back on completion. This ensures that the + # test database remains unchanged so your fixtures don't have to be reloaded + # between every test method. Fewer database queries means faster tests. + # + # Read Mike Clark's excellent walkthrough at + # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting + # + # Every Active Record database supports transactions except MyISAM tables + # in MySQL. Turn off transactional fixtures in this case; however, if you + # don't care one way or the other, switching from MyISAM to InnoDB tables + # is recommended. + self.use_transactional_fixtures = true + + # Instantiated fixtures are slow, but give you @david where otherwise you + # would need people(:david). If you don't want to migrate your existing + # test cases which use the @david style and don't mind the speed hit (each + # instantiated fixtures translates to a database query per test method), + # then set this back to true. + self.use_instantiated_fixtures = false + + # Add more helper methods to be used by all tests here... +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/address_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/address_test.rb new file mode 100644 index 0000000..764f01a --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/address_test.rb @@ -0,0 +1,10 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class AddressTest < Test::Unit::TestCase + fixtures :addresses + + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citation_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citation_test.rb new file mode 100644 index 0000000..113444f --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citation_test.rb @@ -0,0 +1,10 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class CitationTest < Test::Unit::TestCase + fixtures :citations + + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citations_item_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citations_item_test.rb new file mode 100644 index 0000000..0760753 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/citations_item_test.rb @@ -0,0 +1,10 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class CitationsItemTest < Test::Unit::TestCase + fixtures :citations_items + + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/seller_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/seller_test.rb new file mode 100644 index 0000000..69739a7 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/seller_test.rb @@ -0,0 +1,10 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class SellerTest < Test::Unit::TestCase + fixtures :sellers + + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/state_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/state_test.rb new file mode 100644 index 0000000..43b94db --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/state_test.rb @@ -0,0 +1,10 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class StatesTest < Test::Unit::TestCase + fixtures :states + + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/user_test.rb b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/user_test.rb new file mode 100644 index 0000000..5468f7a --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/integration/app/test/unit/user_test.rb @@ -0,0 +1,10 @@ +require File.dirname(__FILE__) + '/../test_helper' + +class UserTest < Test::Unit::TestCase + fixtures :users + + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/models/aquatic/fish.rb b/vendor/plugins/has_many_polymorphs/test/models/aquatic/fish.rb new file mode 100644 index 0000000..204642e --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/aquatic/fish.rb @@ -0,0 +1,5 @@ +class Aquatic::Fish < ActiveRecord::Base + # set_table_name "fish" + # attr_accessor :after_find_test, :after_initialize_test +end + diff --git a/vendor/plugins/has_many_polymorphs/test/models/aquatic/pupils_whale.rb b/vendor/plugins/has_many_polymorphs/test/models/aquatic/pupils_whale.rb new file mode 100644 index 0000000..ae4cbc1 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/aquatic/pupils_whale.rb @@ -0,0 +1,7 @@ + +class Aquatic::PupilsWhale < ActiveRecord::Base + set_table_name "little_whale_pupils" + belongs_to :whale, :class_name => "Aquatic::Whale", :foreign_key => "whale_id" + belongs_to :aquatic_pupil, :polymorphic => true +end + diff --git a/vendor/plugins/has_many_polymorphs/test/models/aquatic/whale.rb b/vendor/plugins/has_many_polymorphs/test/models/aquatic/whale.rb new file mode 100644 index 0000000..0ca1b7f --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/aquatic/whale.rb @@ -0,0 +1,15 @@ +# see http://dev.rubyonrails.org/ticket/5935 +module Aquatic; end +require 'aquatic/fish' +require 'aquatic/pupils_whale' + +class Aquatic::Whale < ActiveRecord::Base + # set_table_name "whales" + + has_many_polymorphs(:aquatic_pupils, :from => [:dogs, :"aquatic/fish"], + :through => "aquatic/pupils_whales") do + def a_method + :correct_block_result + end + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/models/beautiful_fight_relationship.rb b/vendor/plugins/has_many_polymorphs/test/models/beautiful_fight_relationship.rb new file mode 100644 index 0000000..b678c98 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/beautiful_fight_relationship.rb @@ -0,0 +1,26 @@ + +require 'extension_module' + +class BeautifulFightRelationship < ActiveRecord::Base + set_table_name 'keep_your_enemies_close' + + belongs_to :enemy, :polymorphic => true + belongs_to :protector, :polymorphic => true + # polymorphic relationships with column names different from the relationship name + # are not supported by Rails + + acts_as_double_polymorphic_join :enemies => [:dogs, :kittens, :frogs], + :protectors => [:wild_boars, :kittens, :"aquatic/fish", :dogs], + :enemies_extend => [ExtensionModule, proc {}], + :protectors_extend => proc { + def a_method + :correct_proc_result + end + }, + :join_extend => proc { + def a_method + :correct_join_result + end + } +end + diff --git a/vendor/plugins/has_many_polymorphs/test/models/canine.rb b/vendor/plugins/has_many_polymorphs/test/models/canine.rb new file mode 100644 index 0000000..b001016 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/canine.rb @@ -0,0 +1,9 @@ +class Canine < ActiveRecord::Base + self.abstract_class = true + + def an_abstract_method + :correct_abstract_method_response + end + +end + diff --git a/vendor/plugins/has_many_polymorphs/test/models/cat.rb b/vendor/plugins/has_many_polymorphs/test/models/cat.rb new file mode 100644 index 0000000..0c99ff0 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/cat.rb @@ -0,0 +1,5 @@ +class Cat < ActiveRecord::Base + # STI base class + self.inheritance_column = 'cat_type' +end + diff --git a/vendor/plugins/has_many_polymorphs/test/models/dog.rb b/vendor/plugins/has_many_polymorphs/test/models/dog.rb new file mode 100644 index 0000000..7f02723 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/dog.rb @@ -0,0 +1,18 @@ + +require 'canine' + +class Dog < Canine + attr_accessor :after_find_test, :after_initialize_test + set_table_name "bow_wows" + + def after_find + @after_find_test = true +# puts "After find called on #{name}." + end + + def after_initialize + @after_initialize_test = true + end + +end + diff --git a/vendor/plugins/has_many_polymorphs/test/models/eaters_foodstuff.rb b/vendor/plugins/has_many_polymorphs/test/models/eaters_foodstuff.rb new file mode 100644 index 0000000..d904bb1 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/eaters_foodstuff.rb @@ -0,0 +1,10 @@ + +class EatersFoodstuff < ActiveRecord::Base + belongs_to :foodstuff, :class_name => "Petfood", :foreign_key => "foodstuff_id" + belongs_to :eater, :polymorphic => true + + def before_save + self.some_attribute = 3 + end +end + diff --git a/vendor/plugins/has_many_polymorphs/test/models/frog.rb b/vendor/plugins/has_many_polymorphs/test/models/frog.rb new file mode 100644 index 0000000..5a0f465 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/frog.rb @@ -0,0 +1,4 @@ +class Frog < ActiveRecord::Base + +end + diff --git a/vendor/plugins/has_many_polymorphs/test/models/kitten.rb b/vendor/plugins/has_many_polymorphs/test/models/kitten.rb new file mode 100644 index 0000000..2a244c0 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/kitten.rb @@ -0,0 +1,3 @@ +class Kitten < Cat +# has_many :eaters_parents, :dependent => true, :as => 'eater' +end \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/models/parentship.rb b/vendor/plugins/has_many_polymorphs/test/models/parentship.rb new file mode 100644 index 0000000..e87b759 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/parentship.rb @@ -0,0 +1,4 @@ +class Parentship < ActiveRecord::Base + belongs_to :parent, :class_name => "Person", :foreign_key => "parent_id" + belongs_to :kid, :polymorphic => true, :foreign_type => "child_type" +end diff --git a/vendor/plugins/has_many_polymorphs/test/models/person.rb b/vendor/plugins/has_many_polymorphs/test/models/person.rb new file mode 100644 index 0000000..5d01982 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/person.rb @@ -0,0 +1,9 @@ +require 'parentship' +class Person < ActiveRecord::Base + has_many_polymorphs :kids, + :through => :parentships, + :from => [:people], + :as => :parent, + :polymorphic_type_key => "child_type", + :conditions => "people.age < 10" +end diff --git a/vendor/plugins/has_many_polymorphs/test/models/petfood.rb b/vendor/plugins/has_many_polymorphs/test/models/petfood.rb new file mode 100644 index 0000000..df420ea --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/petfood.rb @@ -0,0 +1,39 @@ +# see http://dev.rubyonrails.org/ticket/5935 +require 'eaters_foodstuff' +require 'petfood' +require 'cat' +module Aquatic; end +require 'aquatic/fish' +require 'dog' +require 'wild_boar' +require 'kitten' +require 'tabby' +require 'extension_module' +require 'other_extension_module' + +class Petfood < ActiveRecord::Base + set_primary_key 'the_petfood_primary_key' + has_many_polymorphs :eaters, + :from => [:dogs, :petfoods, :wild_boars, :kittens, + :tabbies, :"aquatic/fish"], +# :dependent => :destroy, :destroy is now the default + :rename_individual_collections => true, + :as => :foodstuff, + :foreign_key => "foodstuff_id", + :ignore_duplicates => false, + :conditions => "NULL IS NULL", + :order => "eaters_foodstuffs.updated_at ASC", + :parent_order => "petfoods.the_petfood_primary_key DESC", + :parent_conditions => "petfoods.name IS NULL OR petfoods.name != 'Snausages'", + :extend => [ExtensionModule, OtherExtensionModule, proc {}], + :join_extend => proc { + def a_method + :correct_join_result + end + }, + :parent_extend => proc { + def a_method + :correct_parent_proc_result + end + } + end diff --git a/vendor/plugins/has_many_polymorphs/test/models/tabby.rb b/vendor/plugins/has_many_polymorphs/test/models/tabby.rb new file mode 100644 index 0000000..3cd0f99 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/tabby.rb @@ -0,0 +1,2 @@ +class Tabby < Cat +end \ No newline at end of file diff --git a/vendor/plugins/has_many_polymorphs/test/models/wild_boar.rb b/vendor/plugins/has_many_polymorphs/test/models/wild_boar.rb new file mode 100644 index 0000000..27d36a5 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/models/wild_boar.rb @@ -0,0 +1,3 @@ +class WildBoar < ActiveRecord::Base +end + diff --git a/vendor/plugins/has_many_polymorphs/test/modules/extension_module.rb b/vendor/plugins/has_many_polymorphs/test/modules/extension_module.rb new file mode 100644 index 0000000..7cb4eff --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/modules/extension_module.rb @@ -0,0 +1,9 @@ + +module ExtensionModule + def a_method + :correct_module_result + end + def self.a_method + :incorrect_module_result + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/modules/other_extension_module.rb b/vendor/plugins/has_many_polymorphs/test/modules/other_extension_module.rb new file mode 100644 index 0000000..16313bd --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/modules/other_extension_module.rb @@ -0,0 +1,9 @@ + +module OtherExtensionModule + def another_method + :correct_other_module_result + end + def self.another_method + :incorrect_other_module_result + end +end diff --git a/vendor/plugins/has_many_polymorphs/test/schema.rb b/vendor/plugins/has_many_polymorphs/test/schema.rb new file mode 100644 index 0000000..39d869d --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/schema.rb @@ -0,0 +1,87 @@ +ActiveRecord::Schema.define(:version => 0) do + create_table :petfoods, :force => true, :primary_key => :the_petfood_primary_key do |t| + t.column :name, :string + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :bow_wows, :force => true do |t| + t.column :name, :string + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :cats, :force => true do |t| + t.column :name, :string + t.column :cat_type, :string + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :frogs, :force => true do |t| + t.column :name, :string + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :wild_boars, :force => true do |t| + t.column :name, :string + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :eaters_foodstuffs, :force => true do |t| + t.column :foodstuff_id, :integer + t.column :eater_id, :integer + t.column :some_attribute, :integer, :default => 0 + t.column :eater_type, :string + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :fish, :force => true do |t| + t.column :name, :string + t.column :speed, :integer + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :whales, :force => true do |t| + t.column :name, :string + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :little_whale_pupils, :force => true do |t| + t.column :whale_id, :integer + t.column :aquatic_pupil_id, :integer + t.column :aquatic_pupil_type, :string + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :keep_your_enemies_close, :force => true do |t| + t.column :enemy_id, :integer + t.column :enemy_type, :string + t.column :protector_id, :integer + t.column :protector_type, :string + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :parentships, :force => true do |t| + t.column :parent_id, :integer + t.column :child_type, :string + t.column :kid_id, :integer + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + + create_table :people, :force => true do |t| + t.column :name, :string + t.column :age, :integer + t.column :created_at, :datetime, :null => false + t.column :updated_at, :datetime, :null => false + end + +end diff --git a/vendor/plugins/has_many_polymorphs/test/setup.rb b/vendor/plugins/has_many_polymorphs/test/setup.rb new file mode 100644 index 0000000..8e7baad --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/setup.rb @@ -0,0 +1,10 @@ + +# Setup integration system for the integration suite + +Dir.chdir "#{File.dirname(__FILE__)}/integration/app/" do + Dir.chdir "vendor/plugins" do + system("rm has_many_polymorphs; ln -s ../../../../../ has_many_polymorphs") + end + system("rake db:create") + system("rake db:migrate db:fixtures:load") +end diff --git a/vendor/plugins/has_many_polymorphs/test/test_all.rb b/vendor/plugins/has_many_polymorphs/test/test_all.rb new file mode 100644 index 0000000..8280269 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/test_all.rb @@ -0,0 +1,16 @@ + +# Run tests against all Rails versions + +VENDOR_DIR = File.expand_path("~/Desktop/projects/vendor/rails") + +HERE = File.expand_path(File.dirname(__FILE__)) + +Dir["#{VENDOR_DIR}/*"].each do |dir| + puts "\n\n**** #{dir} ****\n\n" + Dir.chdir "#{HERE}/integration/app/vendor" do + system("rm rails; ln -s #{dir} rails") + end + system("ruby #{HERE}/unit/polymorph_test.rb") +end + +system("rm #{HERE}/integration/app/vendor; svn up #{HERE}/integration/app/vendor") diff --git a/vendor/plugins/has_many_polymorphs/test/test_helper.rb b/vendor/plugins/has_many_polymorphs/test/test_helper.rb new file mode 100644 index 0000000..e0cc1b7 --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/test_helper.rb @@ -0,0 +1,35 @@ + +begin + require 'rubygems' + require 'ruby-debug' + Debugger.start +rescue Object +end + +HERE = File.expand_path(File.dirname(__FILE__)) +$LOAD_PATH << HERE + +# require 'integration/app/config/environment' +require 'integration/app/test/test_helper' + +def silently + stderr, $stderr = $stderr, StringIO.new + yield + $stderr = stderr +end + +Inflector.inflections {|i| i.irregular 'fish', 'fish' } + +$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path = HERE + "/fixtures") +$LOAD_PATH.unshift(HERE + "/models") +$LOAD_PATH.unshift(HERE + "/modules") + +class Test::Unit::TestCase + self.use_transactional_fixtures = !(ActiveRecord::Base.connection.is_a? ActiveRecord::ConnectionAdapters::MysqlAdapter rescue false) + self.use_instantiated_fixtures = false +end + +# test schema +silently do + load(HERE + "/schema.rb") +end diff --git a/vendor/plugins/has_many_polymorphs/test/unit/polymorph_test.rb b/vendor/plugins/has_many_polymorphs/test/unit/polymorph_test.rb new file mode 100644 index 0000000..0ca5d1a --- /dev/null +++ b/vendor/plugins/has_many_polymorphs/test/unit/polymorph_test.rb @@ -0,0 +1,714 @@ +require File.dirname(__FILE__) + '/../test_helper' + +require 'dog' +require 'wild_boar' +require 'frog' +require 'cat' +require 'kitten' +require 'aquatic/whale' +require 'aquatic/fish' +require 'aquatic/pupils_whale' +require 'beautiful_fight_relationship' + +class PolymorphTest < Test::Unit::TestCase + + set_fixture_class :bow_wows => Dog + set_fixture_class :keep_your_enemies_close => BeautifulFightRelationship + set_fixture_class :whales => Aquatic::Whale + set_fixture_class :fish => Aquatic::Fish + set_fixture_class :little_whale_pupils => Aquatic::PupilsWhale + + fixtures :cats, :bow_wows, :frogs, :wild_boars, :eaters_foodstuffs, :petfoods, + :fish, :whales, :little_whale_pupils, :keep_your_enemies_close, :people + + def setup + @association_error = ActiveRecord::Associations::PolymorphicError + @kibbles = Petfood.find(1) + @bits = Petfood.find(2) + @shamu = Aquatic::Whale.find(1) + @swimmy = Aquatic::Fish.find(1) + @rover = Dog.find(1) + @spot = Dog.find(2) + @puma = WildBoar.find(1) + @chloe = Kitten.find(1) + @alice = Kitten.find(2) + @toby = Tabby.find(3) + @froggy = Frog.find(1) + + @join_count = EatersFoodstuff.count + @kibbles_eaters_count = @kibbles.eaters.size + @bits_eaters_count = @bits.eaters.size + + @double_join_count = BeautifulFightRelationship.count + @alice_enemies_count = @alice.enemies.size + end + + def test_all_relationship_validities + # q = [] + # ObjectSpace.each_object(Class){|c| q << c if c.ancestors.include? ActiveRecord::Base } + # q.each{|c| puts "#{c.name}.reflect_on_all_associations.map &:check_validity! "} + Petfood.reflect_on_all_associations.map &:check_validity! + Tabby.reflect_on_all_associations.map &:check_validity! + Kitten.reflect_on_all_associations.map &:check_validity! + Dog.reflect_on_all_associations.map &:check_validity! + Canine.reflect_on_all_associations.map &:check_validity! + Aquatic::Fish.reflect_on_all_associations.map &:check_validity! + EatersFoodstuff.reflect_on_all_associations.map &:check_validity! + WildBoar.reflect_on_all_associations.map &:check_validity! + Frog.reflect_on_all_associations.map &:check_validity! + Cat.reflect_on_all_associations.map &:check_validity! + BeautifulFightRelationship.reflect_on_all_associations.map &:check_validity! + Person.reflect_on_all_associations.map &:check_validity! + Parentship.reflect_on_all_associations.map &:check_validity! + Aquatic::Whale.reflect_on_all_associations.map &:check_validity! + Aquatic::PupilsWhale.reflect_on_all_associations.map &:check_validity! + end + + def test_assignment + assert @kibbles.eaters.blank? + assert @kibbles.eaters.push(Cat.find_by_name('Chloe')) + assert_equal @kibbles_eaters_count += 1, @kibbles.eaters.count + + @kibbles.reload + assert_equal @kibbles_eaters_count, @kibbles.eaters.count + end + + def test_duplicate_assignment + # try to add a duplicate item when :ignore_duplicates is false + @kibbles.eaters.push(@alice) + assert @kibbles.eaters.include?(@alice) + @kibbles.eaters.push(@alice) + assert_equal @kibbles_eaters_count + 2, @kibbles.eaters.count + assert_equal @join_count + 2, EatersFoodstuff.count + end + + def test_create_and_push + assert @kibbles.eaters.push(@spot) + assert_equal @kibbles_eaters_count += 1, @kibbles.eaters.count + assert @kibbles.eaters << @rover + assert @kibbles.eaters << Kitten.create(:name => "Miranda") + assert_equal @kibbles_eaters_count += 2, @kibbles.eaters.length + + @kibbles.reload + assert_equal @kibbles_eaters_count, @kibbles.eaters.length + + # test that ids and new flags were set appropriately + assert_not_nil @kibbles.eaters[0].id + assert !@kibbles.eaters[1].new_record? + end + + def test_reload + assert @kibbles.reload + assert @kibbles.eaters.reload + end + + def test_add_join_record + assert_equal Kitten, @chloe.class + assert join = EatersFoodstuff.new(:foodstuff_id => @bits.id, :eater_id => @chloe.id, :eater_type => @chloe.class.name ) + assert join.save! + assert join.id + assert_equal @join_count + 1, EatersFoodstuff.count + + #assert_equal @bits_eaters_count, @bits.eaters.size # Doesn't behave this way on latest edge anymore + assert_equal @bits_eaters_count + 1, @bits.eaters.count # SQL + + # reload; is the new association there? + assert @bits.eaters.reload + assert @bits.eaters.include?(@chloe) + end + + def test_build_join_record_on_association + assert_equal Kitten, @chloe.class + assert join = @chloe.eaters_foodstuffs.build(:foodstuff => @bits) + # assert_equal join.eater_type, @chloe.class.name # will be STI parent type + assert join.save! + assert join.id + assert_equal @join_count + 1, EatersFoodstuff.count + + assert @bits.eaters.reload + assert @bits.eaters.include?(@chloe) + end + +# not supporting this, since has_many :through doesn't support it either +# def test_add_unsaved +# # add an unsaved item +# assert @bits.eaters << Kitten.new(:name => "Bridget") +# assert_nil Kitten.find_by_name("Bridget") +# assert_equal @bits_eaters_count + 1, @bits.eaters.count +# +# assert @bits.save +# @bits.reload +# assert_equal @bits_eaters_count + 1, @bits.eaters.count +# +# end + + def test_self_reference + assert @kibbles.eaters << @bits + assert_equal @kibbles_eaters_count += 1, @kibbles.eaters.count + assert @kibbles.eaters.include?(@bits) + @kibbles.reload + assert @kibbles.foodstuffs_of_eaters.blank? + + @bits.reload + assert @bits.foodstuffs_of_eaters.include?(@kibbles) + assert_equal [@kibbles], @bits.foodstuffs_of_eaters + end + + def test_remove + assert @kibbles.eaters << @chloe + @kibbles.reload + assert @kibbles.eaters.delete(@kibbles.eaters[0]) + assert_equal @kibbles_eaters_count, @kibbles.eaters.count + end + + def test_destroy + assert @kibbles.eaters.push(@chloe) + @kibbles.reload + assert @kibbles.eaters.length > 0 + assert @kibbles.eaters[0].destroy + @kibbles.reload + assert_equal @kibbles_eaters_count, @kibbles.eaters.count + end + + def test_clear + @kibbles.eaters << [@chloe, @spot, @rover] + @kibbles.reload + assert @kibbles.eaters.clear.blank? + assert @kibbles.eaters.blank? + @kibbles.reload + assert @kibbles.eaters.blank? + end + + def test_individual_collections + assert @kibbles.eaters.push(@chloe) + # check if individual collections work + assert_equal @kibbles.eater_kittens.length, 1 + assert @kibbles.eater_dogs + assert 1, @rover.eaters_foodstuffs.count + end + + def test_individual_collections_push + assert_equal [@chloe], (@kibbles.eater_kittens << @chloe) + @kibbles.reload + assert @kibbles.eaters.include?(@chloe) + assert @kibbles.eater_kittens.include?(@chloe) + assert !@kibbles.eater_dogs.include?(@chloe) + end + + def test_individual_collections_delete + @kibbles.eaters << [@chloe, @spot, @rover] + @kibbles.reload + assert_equal [@chloe], @kibbles.eater_kittens.delete(@chloe) + assert @kibbles.eater_kittens.empty? + @kibbles.eater_kittens.delete(@chloe) # what should this return? + + @kibbles.reload + assert @kibbles.eater_kittens.empty? + assert @kibbles.eater_dogs.include?(@spot) + end + + def test_individual_collections_clear + @kibbles.eaters << [@chloe, @spot, @rover] + @kibbles.reload + + assert_equal [], @kibbles.eater_kittens.clear + assert @kibbles.eater_kittens.empty? + assert_equal 2, @kibbles.eaters.size + + assert @kibbles.eater_kittens.empty? + assert_equal 2, @kibbles.eaters.size + assert !@kibbles.eater_kittens.include?(@chloe) + assert !@kibbles.eaters.include?(@chloe) + + @kibbles.reload + assert @kibbles.eater_kittens.empty? + assert_equal 2, @kibbles.eaters.size + assert !@kibbles.eater_kittens.include?(@chloe) + assert !@kibbles.eaters.include?(@chloe) + end + + def test_childrens_individual_collections + assert Cat.find_by_name('Chloe').eaters_foodstuffs + assert @kibbles.eaters_foodstuffs + end + + def test_self_referential_join_tables + # check that the self-reference join tables go the right ways + assert_equal @kibbles_eaters_count, @kibbles.eaters_foodstuffs.count + assert_equal @kibbles.eaters_foodstuffs.count, @kibbles.eaters_foodstuffs_as_child.count + end + + def test_dependent + assert @kibbles.eaters << @chloe + @kibbles.reload + + # delete ourself and see if :dependent was obeyed + dependent_rows = @kibbles.eaters_foodstuffs + assert_equal dependent_rows.length, @kibbles.eaters.count + @join_count = EatersFoodstuff.count + + @kibbles.destroy + assert_equal @join_count - dependent_rows.length, EatersFoodstuff.count + assert_equal 0, EatersFoodstuff.find(:all, :conditions => ['foodstuff_id = ?', 1] ).length + end + + def test_normal_callbacks + assert @rover.respond_to?(:after_initialize) + assert @rover.respond_to?(:after_find) + assert @rover.after_initialize_test + assert @rover.after_find_test + end + + def test_model_callbacks_not_overridden_by_plugin_callbacks + assert 0, @bits.eaters.count + assert @bits.eaters.push(@rover) + @bits.save + @bits2 = Petfood.find_by_name("Bits") + @bits.reload + assert rover = @bits2.eaters.select { |x| x.name == "Rover" }[0] + assert rover.after_initialize_test + assert rover.after_find_test + end + + def test_number_of_join_records + assert EatersFoodstuff.create(:foodstuff_id => 1, :eater_id => 1, :eater_type => "Cat") + @join_count = EatersFoodstuff.count + assert @join_count > 0 + end + + def test_number_of_regular_records + dogs = Dog.count + assert Dog.new(:name => "Auggie").save! + assert dogs + 1, Dog.count + end + + def test_attributes_come_through_when_child_has_underscore_in_table_name + join = EatersFoodstuff.new(:foodstuff_id => @bits.id, :eater_id => @puma.id, :eater_type => @puma.class.name) + join.save! + + @bits.eaters.reload + + assert_equal "Puma", @puma.name + assert_equal "Puma", @bits.eaters.first.name + end + + + def test_before_save_on_join_table_is_not_clobbered_by_sti_base_class_fix + assert @kibbles.eaters << @chloe + assert_equal 3, @kibbles.eaters_foodstuffs.first.some_attribute + end + + def test_sti_type_counts_are_correct + @kibbles.eaters << [@chloe, @alice, @toby] + assert_equal 2, @kibbles.eater_kittens.count + assert_equal 1, @kibbles.eater_tabbies.count + assert !@kibbles.respond_to?(:eater_cats) + end + + + def test_creating_namespaced_relationship + assert @shamu.aquatic_pupils.empty? + @shamu.aquatic_pupils << @swimmy + assert_equal 1, @shamu.aquatic_pupils.length + @shamu.reload + assert_equal 1, @shamu.aquatic_pupils.length + end + + def test_namespaced_polymorphic_collection + @shamu.aquatic_pupils << @swimmy + assert @shamu.aquatic_pupils.include?(@swimmy) + @shamu.reload + assert @shamu.aquatic_pupils.include?(@swimmy) + + @shamu.aquatic_pupils << @spot + assert @shamu.dogs.include?(@spot) + assert @shamu.aquatic_pupils.include?(@swimmy) + assert_equal @swimmy, @shamu.aquatic_fish.first + assert_equal 10, @shamu.aquatic_fish.first.speed + end + + def test_deleting_namespaced_relationship + @shamu.aquatic_pupils << @swimmy + @shamu.aquatic_pupils << @spot + + @shamu.reload + @shamu.aquatic_pupils.delete @spot + assert !@shamu.dogs.include?(@spot) + assert !@shamu.aquatic_pupils.include?(@spot) + assert_equal 1, @shamu.aquatic_pupils.length + end + + def test_unrenamed_parent_of_namespaced_child + @shamu.aquatic_pupils << @swimmy + assert_equal [@shamu], @swimmy.whales + end + + def test_empty_double_collections + assert @puma.enemies.empty? + assert @froggy.protectors.empty? + assert @alice.enemies.empty? + assert @spot.protectors.empty? + assert @alice.beautiful_fight_relationships_as_enemy.empty? + assert @alice.beautiful_fight_relationships_as_protector.empty? + assert @alice.beautiful_fight_relationships.empty? + end + + def test_double_collection_assignment + @alice.enemies << @spot + @alice.reload + @spot.reload + assert @spot.protectors.include?(@alice) + assert @alice.enemies.include?(@spot) + assert !@alice.protectors.include?(@alice) + assert_equal 1, @alice.beautiful_fight_relationships_as_protector.size + assert_equal 0, @alice.beautiful_fight_relationships_as_enemy.size + assert_equal 1, @alice.beautiful_fight_relationships.size + + # self reference + assert_equal 1, @alice.enemies.length + @alice.enemies.push @alice + assert @alice.enemies.include?(@alice) + assert_equal 2, @alice.enemies.length + @alice.reload + assert_equal 2, @alice.beautiful_fight_relationships_as_protector.size + assert_equal 1, @alice.beautiful_fight_relationships_as_enemy.size + assert_equal 3, @alice.beautiful_fight_relationships.size + end + + def test_double_collection_build_join_record_on_association + + join = @alice.beautiful_fight_relationships_as_protector.build(:enemy => @spot) + + assert_equal @alice.class.base_class.name, join.protector_type + assert_nothing_raised { join.save! } + + assert join.id + assert_equal @double_join_count + 1, BeautifulFightRelationship.count + + assert @alice.enemies.reload + assert @alice.enemies.include?(@spot) + end + + def test_double_dependency_injection +# breakpoint + end + + def test_double_collection_deletion + @alice.enemies << @spot + @alice.reload + assert @alice.enemies.include?(@spot) + @alice.enemies.delete(@spot) + assert !@alice.enemies.include?(@spot) + assert @alice.enemies.empty? + @alice.reload + assert !@alice.enemies.include?(@spot) + assert @alice.enemies.empty? + assert_equal 0, @alice.beautiful_fight_relationships.size + end + + def test_double_collection_deletion_from_opposite_side + @alice.protectors << @puma + @alice.reload + assert @alice.protectors.include?(@puma) + @alice.protectors.delete(@puma) + assert !@alice.protectors.include?(@puma) + assert @alice.protectors.empty? + @alice.reload + assert !@alice.protectors.include?(@puma) + assert @alice.protectors.empty? + assert_equal 0, @alice.beautiful_fight_relationships.size + end + + def test_individual_collections_created_for_double_relationship + assert @alice.dogs.empty? + @alice.enemies << @spot + + assert @alice.enemies.include?(@spot) + assert !@alice.kittens.include?(@alice) + + assert !@alice.dogs.include?(@spot) + @alice.reload + assert @alice.dogs.include?(@spot) + assert !WildBoar.find(@alice.id).dogs.include?(@spot) # make sure the parent type is checked + end + + def test_individual_collections_created_for_double_relationship_from_opposite_side + assert @alice.wild_boars.empty? + @alice.protectors << @puma + + assert @alice.protectors.include?(@puma) + assert !@alice.wild_boars.include?(@puma) + @alice.reload + assert @alice.wild_boars.include?(@puma) + + assert !Dog.find(@alice.id).wild_boars.include?(@puma) # make sure the parent type is checked + end + + def test_self_referential_individual_collections_created_for_double_relationship + @alice.enemies << @alice + @alice.reload + assert @alice.enemy_kittens.include?(@alice) + assert @alice.protector_kittens.include?(@alice) + assert @alice.kittens.include?(@alice) + assert_equal 2, @alice.kittens.size + + @alice.enemies << (@chloe = Kitten.find_by_name('Chloe')) + @alice.reload + assert @alice.enemy_kittens.include?(@chloe) + assert !@alice.protector_kittens.include?(@chloe) + assert @alice.kittens.include?(@chloe) + assert_equal 3, @alice.kittens.size + end + + def test_child_of_polymorphic_join_can_reach_parent + @alice.enemies << @spot + @alice.reload + assert @spot.protectors.include?(@alice) + end + + def test_double_collection_deletion_from_child_polymorphic_join + @alice.enemies << @spot + @spot.protectors.delete(@alice) + assert !@spot.protectors.include?(@alice) + @alice.reload + assert !@alice.enemies.include?(@spot) + BeautifulFightRelationship.create(:protector_id => 2, :protector_type => "Dog", :enemy_id => @spot.id, :enemy_type => @spot.class.name) + @alice.enemies << @spot + @spot.protectors.delete(@alice) + assert !@spot.protectors.include?(@alice) + end + + def test_collection_query_on_unsaved_record + assert Dog.new.enemies.empty? + assert Dog.new.foodstuffs_of_eaters.empty? + end + + def test_double_individual_collections_push + assert_equal [@chloe], (@spot.protector_kittens << @chloe) + @spot.reload + assert @spot.protectors.include?(@chloe) + assert @spot.protector_kittens.include?(@chloe) + assert !@spot.protector_dogs.include?(@chloe) + + assert_equal [@froggy], (@spot.frogs << @froggy) + @spot.reload + assert @spot.enemies.include?(@froggy) + assert @spot.frogs.include?(@froggy) + assert !@spot.enemy_dogs.include?(@froggy) + end + + def test_double_individual_collections_delete + @spot.protectors << [@chloe, @puma] + @spot.reload + assert_equal [@chloe], @spot.protector_kittens.delete(@chloe) + assert @spot.protector_kittens.empty? + @spot.protector_kittens.delete(@chloe) # again, unclear what .delete should return + + @spot.reload + assert @spot.protector_kittens.empty? + assert @spot.wild_boars.include?(@puma) + end + + def test_double_individual_collections_clear + @spot.protectors << [@chloe, @puma, @alice] + @spot.reload + assert_equal [], @spot.protector_kittens.clear + assert @spot.protector_kittens.empty? + assert_equal 1, @spot.protectors.size + @spot.reload + assert @spot.protector_kittens.empty? + assert_equal 1, @spot.protectors.size + assert !@spot.protector_kittens.include?(@chloe) + assert !@spot.protectors.include?(@chloe) + assert !@spot.protector_kittens.include?(@alice) + assert !@spot.protectors.include?(@alice) + assert @spot.protectors.include?(@puma) + assert @spot.wild_boars.include?(@puma) + end + + def test_single_extensions + assert_equal :correct_block_result, @shamu.aquatic_pupils.a_method + @kibbles.eaters.push(@alice) + @kibbles.eaters.push(@spot) + assert_equal :correct_join_result, @kibbles.eaters_foodstuffs.a_method + assert_equal :correct_module_result, @kibbles.eaters.a_method + assert_equal :correct_other_module_result, @kibbles.eaters.another_method + @kibbles.eaters.each do |eater| + assert_equal :correct_join_result, eater.eaters_foodstuffs.a_method + end + assert_equal :correct_parent_proc_result, @kibbles.foodstuffs_of_eaters.a_method + assert_equal :correct_parent_proc_result, @kibbles.eaters.first.foodstuffs_of_eaters.a_method + end + + def test_double_extensions + assert_equal :correct_proc_result, @spot.protectors.a_method + assert_equal :correct_module_result, @spot.enemies.a_method + assert_equal :correct_join_result, @spot.beautiful_fight_relationships_as_enemy.a_method + assert_equal :correct_join_result, @spot.beautiful_fight_relationships_as_protector.a_method + assert_equal :correct_join_result, @froggy.beautiful_fight_relationships.a_method + assert_equal :correct_join_result, @froggy.beautiful_fight_relationships_as_enemy.a_method + assert_raises(NoMethodError) {@froggy.beautiful_fight_relationships_as_protector.a_method} + end + + def test_pluralization_checks + assert_raises(@association_error) { + eval "class SomeModel < ActiveRecord::Base + has_many_polymorphs :polymorphs, :from => [:dog, :cats] + end" } + assert_raises(@association_error) { + eval "class SomeModel < ActiveRecord::Base + has_many_polymorphs :polymorph, :from => [:dogs, :cats] + end" } + assert_raises(@association_error) { + eval "class SomeModel < ActiveRecord::Base + acts_as_double_polymorphic_join :polymorph => [:dogs, :cats], :unimorphs => [:dogs, :cats] + end" } + end + + def test_error_message_on_namespaced_targets + assert_raises(@association_error) { + eval "class SomeModel < ActiveRecord::Base + has_many_polymorphs :polymorphs, :from => [:fish] + end" } + end + + def test_single_custom_finders + [@kibbles, @alice, @puma, @spot, @bits].each {|record| @kibbles.eaters << record; sleep 1} # XXX yeah i know + assert_equal @kibbles.eaters, @kibbles.eaters.find(:all, :order => "eaters_foodstuffs.created_at ASC") + assert_equal @kibbles.eaters.reverse, @kibbles.eaters.find(:all, :order => "eaters_foodstuffs.created_at DESC") + if (ActiveRecord::Base.connection.is_a? ActiveRecord::ConnectionAdapters::MysqlAdapter rescue false) + assert_equal @kibbles.eaters.sort_by(&:created_at), @kibbles.eaters.find(:all, :order => "IFNULL(bow_wows.created_at,(IFNULL(petfoods.created_at,(IFNULL(wild_boars.created_at,(IFNULL(cats.created_at,fish.created_at))))))) ASC") + end + assert_equal @kibbles.eaters.select{|x| x.is_a? Petfood}, @kibbles.eater_petfoods.find(:all, :order => "eaters_foodstuffs.created_at ASC") + end + + def test_double_custom_finders + @spot.protectors << [@chloe, @puma, @alice] + assert_equal [@chloe], @spot.protectors.find(:all, :conditions => ["cats.name = ?", @chloe.name], :limit => 1) + assert_equal [], @spot.protectors.find(:all, :conditions => ["cats.name = ?", @chloe.name], :limit => 1, :offset => 1) + assert_equal 2, @spot.protectors.find(:all, :limit => 100, :offset => 1).size + end + + def test_single_custom_finder_parameters_carry_to_individual_relationships + # XXX test nullout here + end + + def test_double_custom_finder_parameters_carry_to_individual_relationships + # XXX test nullout here + end + + def test_include_doesnt_fail + assert_nothing_raised do + @spot.protectors.find(:all, :include => :wild_boars) + end + end + + def test_abstract_method + assert_equal :correct_abstract_method_response, @spot.an_abstract_method + end + + def test_missing_target_should_raise + @kibbles.eaters << [@kibbles, @alice, @puma, @spot, @bits] + @spot.destroy_without_callbacks + assert_raises(@association_error) { @kibbles.eaters.reload } +# assert_raises(@association_error) { @kibbles.eater_dogs.reload } # bah AR + end + + def test_lazy_loading_is_lazy + # XXX + end + + def test_push_with_skip_duplicates_false_doesnt_load_target + # Loading kibbles locally again because setup calls .size which loads target + kibbles = Petfood.find(1) + assert !kibbles.eaters.loaded? + assert !(kibbles.eater_dogs << Dog.create!(:name => "Mongy")).loaded? + assert !kibbles.eaters.loaded? + end + + def test_association_foreign_key_is_sane + assert_equal "eater_id", Petfood.reflect_on_association(:eaters).association_foreign_key + end + + def test_reflection_instance_methods_are_sane + assert_equal EatersFoodstuff, Petfood.reflect_on_association(:eaters).klass + assert_equal EatersFoodstuff.name, Petfood.reflect_on_association(:eaters).class_name + end + + def test_parent_order + @alice.foodstuffs_of_eaters << Petfood.find(:all, :order => "the_petfood_primary_key ASC") + @alice.reload #not necessary + assert_equal [2,1], @alice.foodstuffs_of_eaters.map(&:id) + end + + def test_parent_conditions + @kibbles.eaters << @alice + assert_equal [@alice], @kibbles.eaters + + @snausages = Petfood.create(:name => 'Snausages') + @snausages.eaters << @alice + assert_equal [@alice], @snausages.eaters + + assert_equal [@kibbles], @alice.foodstuffs_of_eaters + end + + def test_self_referential_hmp_with_conditions + p = Person.find(:first) + kid = Person.create(:name => "Tim", :age => 3) + p.kids << kid + + kid.reload; p.reload + + # assert_equal [p], kid.parents + # assert Rails.has_one? Bug + # non-standard foreign_type key is not set properly when you are the polymorphic interface of a has_many going to a :through + + assert_equal [kid], p.kids + assert_equal [kid], p.people + end + +# def test_polymorphic_include +# @kibbles.eaters << [@kibbles, @alice, @puma, @spot, @bits] +# assert @kibbles.eaters.include?(@kibbles.eaters_foodstuffs.find(:all, :include => :eater).first.eater) +# end +# +# def test_double_polymorphic_include +# end +# +# def test_single_child_include +# end +# +# def test_double_child_include +# end +# +# def test_single_include_from_parent +# end +# +# def test_double_include_from_parent +# end +# +# def test_meta_referential_single_include +# end +# +# def test_meta_referential_double_include +# end +# +# def test_meta_referential_single_include +# end +# +# def test_meta_referential_single_double_multi_include +# end +# +# def test_dont_ignore_duplicates +# end +# +# def test_ignore_duplicates +# end +# +# def test_tagging_system_generator +# end +# +# def test_tagging_system_library +# end + +end