Fix deprecation warning of has_many_polymorphs. Needed to vendor this gem.

This commit is contained in:
Reinier Balt 2012-04-08 15:17:29 +02:00
parent affb802791
commit 2bdecb583a
177 changed files with 11469 additions and 4 deletions

View file

@ -8,7 +8,7 @@ gem "RedCloth", "4.2.8"
gem "sanitize", "~>1.2.1"
gem "rack", "1.1.0"
gem "will_paginate", "~> 2.3.15"
gem "has_many_polymorphs", "~> 2.13"
gem "has_many_polymorphs", "~> 2.13", :path => "vendor/gems/has_many_polymorphs-2.13" # vendorred to get rid of some deprecation warnings
gem "acts_as_list", "~>0.1.4"
gem "aasm", "~>2.2.0"
gem "rubyjedi-actionwebservice", :require => "actionwebservice"

View file

@ -3,6 +3,12 @@ PATH
specs:
aruba (0.2.2)
PATH
remote: vendor/gems/has_many_polymorphs-2.13
specs:
has_many_polymorphs (2.13)
activerecord
GEM
remote: http://rubygems.org/
remote: http://gems.github.com/
@ -51,8 +57,6 @@ GEM
gem_plugin (0.2.3)
gherkin (2.7.7)
json (>= 1.4.6)
has_many_polymorphs (2.13)
activerecord
highline (1.5.2)
hoe (2.13.1)
rake (~> 0.8)
@ -143,7 +147,7 @@ DEPENDENCIES
cucumber-rails (~> 0.3.2)
database_cleaner (>= 0.5.0)
flexmock
has_many_polymorphs (~> 2.13)
has_many_polymorphs (~> 2.13)!
highline (~> 1.5.0)
hoe
hpricot

View file

@ -0,0 +1,288 @@
--- !ruby/object:Gem::Specification
name: has_many_polymorphs
version: !ruby/object:Gem::Version
hash: 25
prerelease:
segments:
- 2
- 13
version: "2.13"
platform: ruby
authors:
- ""
autorequire:
bindir: bin
cert_chain:
- /Users/eweaver/p/configuration/gem_certificates/evan_weaver-original-public_cert.pem
date: 2009-02-02 00:00:00 Z
dependencies:
- !ruby/object:Gem::Dependency
type: :runtime
requirement: &id001 !ruby/object:Gem::Requirement
none: false
requirements:
- - ">="
- !ruby/object:Gem::Version
hash: 3
segments:
- 0
version: "0"
prerelease: false
name: activerecord
version_requirements: *id001
- !ruby/object:Gem::Dependency
type: :development
requirement: &id002 !ruby/object:Gem::Requirement
none: false
requirements:
- - ">="
- !ruby/object:Gem::Version
hash: 3
segments:
- 0
version: "0"
prerelease: false
name: echoe
version_requirements: *id002
description: An ActiveRecord plugin for self-referential and double-sided polymorphic associations.
email: ""
executables: []
extensions: []
extra_rdoc_files:
- CHANGELOG
- generators/tagging/templates/migration.rb
- generators/tagging/templates/tag.rb
- generators/tagging/templates/tagging.rb
- generators/tagging/templates/tagging_extensions.rb
- lib/has_many_polymorphs/association.rb
- lib/has_many_polymorphs/autoload.rb
- lib/has_many_polymorphs/class_methods.rb
- lib/has_many_polymorphs/configuration.rb
- lib/has_many_polymorphs/reflection.rb
- LICENSE
- README
- test/integration/app/doc/README_FOR_APP
- test/integration/app/README
- TODO
files:
- CHANGELOG
- examples/hmph.rb
- generators/tagging/tagging_generator.rb
- generators/tagging/templates/migration.rb
- generators/tagging/templates/tag.rb
- generators/tagging/templates/tag_test.rb
- generators/tagging/templates/tagging.rb
- generators/tagging/templates/tagging_extensions.rb
- generators/tagging/templates/tagging_test.rb
- generators/tagging/templates/taggings.yml
- generators/tagging/templates/tags.yml
- init.rb
- lib/has_many_polymorphs/association.rb
- lib/has_many_polymorphs/autoload.rb
- lib/has_many_polymorphs/base.rb
- lib/has_many_polymorphs/class_methods.rb
- lib/has_many_polymorphs/configuration.rb
- lib/has_many_polymorphs/debugging_tools.rb
- lib/has_many_polymorphs/rake_task_redefine_task.rb
- lib/has_many_polymorphs/reflection.rb
- lib/has_many_polymorphs/support_methods.rb
- lib/has_many_polymorphs.rb
- LICENSE
- Manifest
- Rakefile
- README
- test/fixtures/bow_wows.yml
- test/fixtures/cats.yml
- test/fixtures/eaters_foodstuffs.yml
- test/fixtures/fish.yml
- test/fixtures/frogs.yml
- test/fixtures/keep_your_enemies_close.yml
- test/fixtures/little_whale_pupils.yml
- test/fixtures/people.yml
- test/fixtures/petfoods.yml
- test/fixtures/whales.yml
- test/fixtures/wild_boars.yml
- test/generator/tagging_generator_test.rb
- test/integration/app/app/controllers/application.rb
- test/integration/app/app/controllers/bones_controller.rb
- test/integration/app/app/helpers/addresses_helper.rb
- test/integration/app/app/helpers/application_helper.rb
- test/integration/app/app/helpers/bones_helper.rb
- test/integration/app/app/helpers/sellers_helper.rb
- test/integration/app/app/helpers/states_helper.rb
- test/integration/app/app/helpers/users_helper.rb
- test/integration/app/app/models/bone.rb
- test/integration/app/app/models/double_sti_parent.rb
- test/integration/app/app/models/double_sti_parent_relationship.rb
- test/integration/app/app/models/organic_substance.rb
- test/integration/app/app/models/single_sti_parent.rb
- test/integration/app/app/models/single_sti_parent_relationship.rb
- test/integration/app/app/models/stick.rb
- test/integration/app/app/models/stone.rb
- test/integration/app/app/views/addresses/edit.html.erb
- test/integration/app/app/views/addresses/index.html.erb
- test/integration/app/app/views/addresses/new.html.erb
- test/integration/app/app/views/addresses/show.html.erb
- test/integration/app/app/views/bones/index.rhtml
- test/integration/app/app/views/layouts/addresses.html.erb
- test/integration/app/app/views/layouts/sellers.html.erb
- test/integration/app/app/views/layouts/states.html.erb
- test/integration/app/app/views/layouts/users.html.erb
- test/integration/app/app/views/sellers/edit.html.erb
- test/integration/app/app/views/sellers/index.html.erb
- test/integration/app/app/views/sellers/new.html.erb
- test/integration/app/app/views/sellers/show.html.erb
- test/integration/app/app/views/states/edit.html.erb
- test/integration/app/app/views/states/index.html.erb
- test/integration/app/app/views/states/new.html.erb
- test/integration/app/app/views/states/show.html.erb
- test/integration/app/app/views/users/edit.html.erb
- test/integration/app/app/views/users/index.html.erb
- test/integration/app/app/views/users/new.html.erb
- test/integration/app/app/views/users/show.html.erb
- test/integration/app/config/boot.rb
- test/integration/app/config/database.yml
- test/integration/app/config/environment.rb
- test/integration/app/config/environment.rb.canonical
- test/integration/app/config/environments/development.rb
- test/integration/app/config/environments/production.rb
- test/integration/app/config/environments/test.rb
- test/integration/app/config/locomotive.yml
- test/integration/app/config/routes.rb
- test/integration/app/config/ultrasphinx/default.base
- test/integration/app/config/ultrasphinx/development.conf.canonical
- test/integration/app/db/migrate/001_create_sticks.rb
- test/integration/app/db/migrate/002_create_stones.rb
- test/integration/app/db/migrate/003_create_organic_substances.rb
- test/integration/app/db/migrate/004_create_bones.rb
- test/integration/app/db/migrate/005_create_single_sti_parents.rb
- test/integration/app/db/migrate/006_create_double_sti_parents.rb
- test/integration/app/db/migrate/007_create_single_sti_parent_relationships.rb
- test/integration/app/db/migrate/008_create_double_sti_parent_relationships.rb
- test/integration/app/db/migrate/009_create_library_model.rb
- test/integration/app/doc/README_FOR_APP
- test/integration/app/generators/commenting_generator_test.rb
- test/integration/app/lib/library_model.rb
- test/integration/app/public/404.html
- test/integration/app/public/500.html
- test/integration/app/public/dispatch.cgi
- test/integration/app/public/dispatch.fcgi
- test/integration/app/public/dispatch.rb
- test/integration/app/public/favicon.ico
- test/integration/app/public/images/rails.png
- test/integration/app/public/index.html
- test/integration/app/public/javascripts/application.js
- test/integration/app/public/javascripts/controls.js
- test/integration/app/public/javascripts/dragdrop.js
- test/integration/app/public/javascripts/effects.js
- test/integration/app/public/javascripts/prototype.js
- test/integration/app/public/robots.txt
- test/integration/app/public/stylesheets/scaffold.css
- test/integration/app/Rakefile
- test/integration/app/README
- test/integration/app/script/about
- test/integration/app/script/breakpointer
- test/integration/app/script/console
- test/integration/app/script/destroy
- test/integration/app/script/generate
- test/integration/app/script/performance/benchmarker
- test/integration/app/script/performance/profiler
- test/integration/app/script/plugin
- test/integration/app/script/process/inspector
- test/integration/app/script/process/reaper
- test/integration/app/script/process/spawner
- test/integration/app/script/runner
- test/integration/app/script/server
- test/integration/app/test/fixtures/double_sti_parent_relationships.yml
- test/integration/app/test/fixtures/double_sti_parents.yml
- test/integration/app/test/fixtures/organic_substances.yml
- test/integration/app/test/fixtures/single_sti_parent_relationships.yml
- test/integration/app/test/fixtures/single_sti_parents.yml
- test/integration/app/test/fixtures/sticks.yml
- test/integration/app/test/fixtures/stones.yml
- test/integration/app/test/functional/addresses_controller_test.rb
- test/integration/app/test/functional/bones_controller_test.rb
- test/integration/app/test/functional/sellers_controller_test.rb
- test/integration/app/test/functional/states_controller_test.rb
- test/integration/app/test/functional/users_controller_test.rb
- test/integration/app/test/test_helper.rb
- test/integration/app/test/unit/bone_test.rb
- test/integration/app/test/unit/double_sti_parent_relationship_test.rb
- test/integration/app/test/unit/double_sti_parent_test.rb
- test/integration/app/test/unit/organic_substance_test.rb
- test/integration/app/test/unit/single_sti_parent_relationship_test.rb
- test/integration/app/test/unit/single_sti_parent_test.rb
- test/integration/app/test/unit/stick_test.rb
- test/integration/app/test/unit/stone_test.rb
- test/integration/server_test.rb
- test/models/aquatic/fish.rb
- test/models/aquatic/pupils_whale.rb
- test/models/aquatic/whale.rb
- test/models/beautiful_fight_relationship.rb
- test/models/canine.rb
- test/models/cat.rb
- test/models/dog.rb
- test/models/eaters_foodstuff.rb
- test/models/frog.rb
- test/models/kitten.rb
- test/models/parentship.rb
- test/models/person.rb
- test/models/petfood.rb
- test/models/tabby.rb
- test/models/wild_boar.rb
- test/modules/extension_module.rb
- test/modules/other_extension_module.rb
- test/patches/symlinked_plugins_1.2.6.diff
- test/schema.rb
- test/setup.rb
- test/test_helper.rb
- test/unit/has_many_polymorphs_test.rb
- TODO
- has_many_polymorphs.gemspec
homepage: http://blog.evanweaver.com/files/doc/fauna/has_many_polymorphs/
licenses: []
post_install_message:
rdoc_options:
- --line-numbers
- --inline-source
- --title
- Has_many_polymorphs
- --main
- README
require_paths:
- lib
required_ruby_version: !ruby/object:Gem::Requirement
none: false
requirements:
- - ">="
- !ruby/object:Gem::Version
hash: 3
segments:
- 0
version: "0"
required_rubygems_version: !ruby/object:Gem::Requirement
none: false
requirements:
- - ">="
- !ruby/object:Gem::Version
hash: 11
segments:
- 1
- 2
version: "1.2"
requirements: []
rubyforge_project: fauna
rubygems_version: 1.8.10
signing_key: /Users/eweaver/p/configuration/gem_certificates/evan_weaver-original-private_key.pem
specification_version: 2
summary: An ActiveRecord plugin for self-referential and double-sided polymorphic associations.
test_files:
- test/generator/tagging_generator_test.rb
- test/integration/server_test.rb
- test/unit/has_many_polymorphs_test.rb
has_rdoc: true

View file

@ -0,0 +1,84 @@
v2.13. Merge various fixes for Rails 2.2.2.
v2.12. Improvements to the test suite; bugfixes for STI children (rsl). Remove fancy dependency system in favor of using Dispatcher::to_prepare every time.
v2.11. Rails 1.2.6 tagging generator compatibility; change test suite to use included integration app.
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.

View file

@ -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 <insert your license name here>" 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.

View file

@ -0,0 +1,173 @@
CHANGELOG
examples/hmph.rb
generators/tagging/tagging_generator.rb
generators/tagging/templates/migration.rb
generators/tagging/templates/tag.rb
generators/tagging/templates/tag_test.rb
generators/tagging/templates/tagging.rb
generators/tagging/templates/tagging_extensions.rb
generators/tagging/templates/tagging_test.rb
generators/tagging/templates/taggings.yml
generators/tagging/templates/tags.yml
init.rb
lib/has_many_polymorphs/association.rb
lib/has_many_polymorphs/autoload.rb
lib/has_many_polymorphs/base.rb
lib/has_many_polymorphs/class_methods.rb
lib/has_many_polymorphs/configuration.rb
lib/has_many_polymorphs/debugging_tools.rb
lib/has_many_polymorphs/rake_task_redefine_task.rb
lib/has_many_polymorphs/reflection.rb
lib/has_many_polymorphs/support_methods.rb
lib/has_many_polymorphs.rb
LICENSE
Manifest
Rakefile
README
test/fixtures/bow_wows.yml
test/fixtures/cats.yml
test/fixtures/eaters_foodstuffs.yml
test/fixtures/fish.yml
test/fixtures/frogs.yml
test/fixtures/keep_your_enemies_close.yml
test/fixtures/little_whale_pupils.yml
test/fixtures/people.yml
test/fixtures/petfoods.yml
test/fixtures/whales.yml
test/fixtures/wild_boars.yml
test/generator/tagging_generator_test.rb
test/integration/app/app/controllers/application.rb
test/integration/app/app/controllers/bones_controller.rb
test/integration/app/app/helpers/addresses_helper.rb
test/integration/app/app/helpers/application_helper.rb
test/integration/app/app/helpers/bones_helper.rb
test/integration/app/app/helpers/sellers_helper.rb
test/integration/app/app/helpers/states_helper.rb
test/integration/app/app/helpers/users_helper.rb
test/integration/app/app/models/bone.rb
test/integration/app/app/models/double_sti_parent.rb
test/integration/app/app/models/double_sti_parent_relationship.rb
test/integration/app/app/models/organic_substance.rb
test/integration/app/app/models/single_sti_parent.rb
test/integration/app/app/models/single_sti_parent_relationship.rb
test/integration/app/app/models/stick.rb
test/integration/app/app/models/stone.rb
test/integration/app/app/views/addresses/edit.html.erb
test/integration/app/app/views/addresses/index.html.erb
test/integration/app/app/views/addresses/new.html.erb
test/integration/app/app/views/addresses/show.html.erb
test/integration/app/app/views/bones/index.rhtml
test/integration/app/app/views/layouts/addresses.html.erb
test/integration/app/app/views/layouts/sellers.html.erb
test/integration/app/app/views/layouts/states.html.erb
test/integration/app/app/views/layouts/users.html.erb
test/integration/app/app/views/sellers/edit.html.erb
test/integration/app/app/views/sellers/index.html.erb
test/integration/app/app/views/sellers/new.html.erb
test/integration/app/app/views/sellers/show.html.erb
test/integration/app/app/views/states/edit.html.erb
test/integration/app/app/views/states/index.html.erb
test/integration/app/app/views/states/new.html.erb
test/integration/app/app/views/states/show.html.erb
test/integration/app/app/views/users/edit.html.erb
test/integration/app/app/views/users/index.html.erb
test/integration/app/app/views/users/new.html.erb
test/integration/app/app/views/users/show.html.erb
test/integration/app/config/boot.rb
test/integration/app/config/database.yml
test/integration/app/config/environment.rb
test/integration/app/config/environment.rb.canonical
test/integration/app/config/environments/development.rb
test/integration/app/config/environments/production.rb
test/integration/app/config/environments/test.rb
test/integration/app/config/locomotive.yml
test/integration/app/config/routes.rb
test/integration/app/config/ultrasphinx/default.base
test/integration/app/config/ultrasphinx/development.conf.canonical
test/integration/app/db/migrate/001_create_sticks.rb
test/integration/app/db/migrate/002_create_stones.rb
test/integration/app/db/migrate/003_create_organic_substances.rb
test/integration/app/db/migrate/004_create_bones.rb
test/integration/app/db/migrate/005_create_single_sti_parents.rb
test/integration/app/db/migrate/006_create_double_sti_parents.rb
test/integration/app/db/migrate/007_create_single_sti_parent_relationships.rb
test/integration/app/db/migrate/008_create_double_sti_parent_relationships.rb
test/integration/app/db/migrate/009_create_library_model.rb
test/integration/app/doc/README_FOR_APP
test/integration/app/generators/commenting_generator_test.rb
test/integration/app/lib/library_model.rb
test/integration/app/public/404.html
test/integration/app/public/500.html
test/integration/app/public/dispatch.cgi
test/integration/app/public/dispatch.fcgi
test/integration/app/public/dispatch.rb
test/integration/app/public/favicon.ico
test/integration/app/public/images/rails.png
test/integration/app/public/index.html
test/integration/app/public/javascripts/application.js
test/integration/app/public/javascripts/controls.js
test/integration/app/public/javascripts/dragdrop.js
test/integration/app/public/javascripts/effects.js
test/integration/app/public/javascripts/prototype.js
test/integration/app/public/robots.txt
test/integration/app/public/stylesheets/scaffold.css
test/integration/app/Rakefile
test/integration/app/README
test/integration/app/script/about
test/integration/app/script/breakpointer
test/integration/app/script/console
test/integration/app/script/destroy
test/integration/app/script/generate
test/integration/app/script/performance/benchmarker
test/integration/app/script/performance/profiler
test/integration/app/script/plugin
test/integration/app/script/process/inspector
test/integration/app/script/process/reaper
test/integration/app/script/process/spawner
test/integration/app/script/runner
test/integration/app/script/server
test/integration/app/test/fixtures/double_sti_parent_relationships.yml
test/integration/app/test/fixtures/double_sti_parents.yml
test/integration/app/test/fixtures/organic_substances.yml
test/integration/app/test/fixtures/single_sti_parent_relationships.yml
test/integration/app/test/fixtures/single_sti_parents.yml
test/integration/app/test/fixtures/sticks.yml
test/integration/app/test/fixtures/stones.yml
test/integration/app/test/functional/addresses_controller_test.rb
test/integration/app/test/functional/bones_controller_test.rb
test/integration/app/test/functional/sellers_controller_test.rb
test/integration/app/test/functional/states_controller_test.rb
test/integration/app/test/functional/users_controller_test.rb
test/integration/app/test/test_helper.rb
test/integration/app/test/unit/bone_test.rb
test/integration/app/test/unit/double_sti_parent_relationship_test.rb
test/integration/app/test/unit/double_sti_parent_test.rb
test/integration/app/test/unit/organic_substance_test.rb
test/integration/app/test/unit/single_sti_parent_relationship_test.rb
test/integration/app/test/unit/single_sti_parent_test.rb
test/integration/app/test/unit/stick_test.rb
test/integration/app/test/unit/stone_test.rb
test/integration/server_test.rb
test/models/aquatic/fish.rb
test/models/aquatic/pupils_whale.rb
test/models/aquatic/whale.rb
test/models/beautiful_fight_relationship.rb
test/models/canine.rb
test/models/cat.rb
test/models/dog.rb
test/models/eaters_foodstuff.rb
test/models/frog.rb
test/models/kitten.rb
test/models/parentship.rb
test/models/person.rb
test/models/petfood.rb
test/models/tabby.rb
test/models/wild_boar.rb
test/modules/extension_module.rb
test/modules/other_extension_module.rb
test/patches/symlinked_plugins_1.2.6.diff
test/schema.rb
test/setup.rb
test/test_helper.rb
test/unit/has_many_polymorphs_test.rb
TODO

View file

@ -0,0 +1,205 @@
Has_many_polymorphs
An ActiveRecord plugin for self-referential and double-sided polymorphic associations.
== License
Copyright 2006-2008 Cloudburst, LLC. Licensed under the AFL 3. See the included LICENSE file.
The public certificate for the gem is here[http://rubyforge.org/frs/download.php/25331/evan_weaver-original-public_cert.pem].
If you use this software, please {make a donation}[http://blog.evanweaver.com/donate/], or {recommend Evan}[http://www.workingwithrails.com/person/7739-evan-weaver] at Working with Rails.
== Description
This plugin lets you define self-referential and double-sided polymorphic associations in your models. It is an extension of <tt>has_many :through</tt>.
“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 2.2.2 or greater
= Usage
== Installation
To install the Rails plugin, run:
script/plugin install git://github.com/fauna/has_many_polymorphs.git
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 <tt>require 'has_many_polymorphs'</tt> to <tt>environment.rb</tt>, 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
For your parent and child models, you don't need any special fields in your migration. For the join model (GuestsKennel), use a migration like so:
class CreateGuestsKennels < ActiveRecord::Migration
def self.up
create_table :guests_kennels do |t|
t.references :guest, :polymorphic => true
t.references :kennel
end
end
def self.down
drop_table :guests_kennels
end
end
See ActiveRecord::Associations::PolymorphicClassMethods for more configuration options.
== Helper methods example
>> k = Kennel.find(1)
#<Kennel id: 1, name: "Happy Paws">
>> 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
#<Dog id: 3, name: "Rover">
>> d.kennels
[#<Kennel id: 1, name: "Happy Paws">]
>> 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 (<tt>Dog#kennels</tt>, not <tt>Dog#kennel</tt>).
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 <tt>guests</tt>) and dogs can't be eaten by anything (since they aren't <tt>eatens</tt>). The keys stand for what the models are, not what they do.
In this case, each guest/eaten relationship is called a Devouring.
In your migration, you need to declare both sides as polymorphic:
class CreateDevourings < ActiveRecord::Migration
def self.up
create_table :devourings do |t|
t.references :guest, :polymorphic => true
t.references :eaten, :polymorphic => true
end
end
def self.down
drop_table :devourings
end
end
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 <tt>app/models</tt>. It configures Tag with an appropriate <tt>has_many_polymorphs</tt> call against the models you list at the command line. It also adds the file <tt>lib/tagging_extensions.rb</tt> and <tt>requires</tt> it in <tt>environment.rb</tt>.
Tests will also be generated.
Once you've run the generator, you can tag records as follows:
>> d = Dog.create(:name => "Rover")
#<Dog id: 3, name: "Rover">
>> d.tag_list
""
>> d.tag_with "fierce loud"
#<Dog id: 3, name: "Rover">
>> d.tag_list
"fierce loud"
>> c = Cat.create(:name => "Chloe")
#<Cat id: 1, name: "Chloe">
>> c.tag_with "fierce cute"
#<Cat id: 1, name: "Chloe">
>> c.tag_list
"cute fierce"
>> Tag.find_by_name("fierce").taggables
[#<Cat id: 1, name: "Chloe">, #<Dog id: 3, name: "Rover">]
The generator accepts the optional flag <tt>--skip-migration</tt> to skip generating a migration (for example, if you are converting from <tt>acts_as_taggable</tt>). It also accepts the flag <tt>--self-referential</tt> 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 <tt>lib/has_many_polymorphs/debugging_tools.rb</tt>.
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 <tt>:class_name</tt>, <tt>:foreign_key</tt>, or <tt>:as</tt>. 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 <tt>config.cache_classes = true</tt> in <tt>config/environments/development.rb</tt> to avoid this.
== Reporting problems
The support forum is here[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

View file

@ -0,0 +1,28 @@
require 'echoe'
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
p.clean_pattern += ["**/ruby_sess*", "**/generated_models/**"]
p.test_pattern = ["test/unit/*_test.rb", "test/integration/*_test.rb", "test/generator/*_test.rb"]
end
desc "Run all the tests for every database adapter"
task "test_all" do
['mysql', 'postgresql', 'sqlite3'].each do |adapter|
ENV['DB'] = adapter
ENV['PRODUCTION'] = nil
STDERR.puts "#{'='*80}\nDevelopment mode for #{adapter}\n#{'='*80}"
system("rake test:multi_rails:all")
ENV['PRODUCTION'] = '1'
STDERR.puts "#{'='*80}\nProduction mode for #{adapter}\n#{'='*80}"
system("rake test:multi_rails:all")
end
end

View file

@ -0,0 +1,2 @@
* Tag cloud method

View file

@ -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

View file

@ -0,0 +1,97 @@
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 = {})
parse!(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

View file

@ -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 <tt>acts_as_list</tt>.
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

View file

@ -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 <tt>validates_format_of parameters</tt> 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 <tt>before_save</tt> 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

View file

@ -0,0 +1,15 @@
require File.dirname(__FILE__) + '/../test_helper'
class TagTest < Test::Unit::TestCase
fixtures <%= taggable_models[0..1].join(", ") -%>
def setup
@obj = <%= model_two %>.find(:first)
@obj.tag_with "pale imperial"
end
def test_to_s
assert_equal "imperial pale", <%= model_two -%>.find(:first).tags.to_s
end
end

View file

@ -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 <tt>acts_as_list</tt>, 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 <tt>Tag</tt> is deleted if it no longer tags anything.
def after_destroy
<%= parent_association_name -%>.destroy_without_callbacks if <%= parent_association_name -%> and <%= parent_association_name -%>.taggings.count == 0
end
end

View file

@ -0,0 +1,203 @@
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 <tt>self</tt>. 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?
tags << tag
rescue ActiveRecord::StatementInvalid => e
raise unless e.to_s =~ /duplicate/i
end
end
end
# Removes tags from <tt>self</tt>. 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 <tt>self</tt> as a string.
def tag_list
# Redefined later to avoid an RDoc parse error.
end
# Replace the existing tags on <tt>self</tt>. 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 <tt>self</tt> as a string.
def tag_list #:nodoc:
#:stopdoc:
taggable?(true)
<%= parent_association_name -%>s.reload
<%= parent_association_name -%>s.to_s
#:startdoc:
end
def tag_list=(value)
tag_with(value)
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
module TaggingFinders
# Find all the objects tagged with the supplied list of tags
#
# Usage : Model.tagged_with("ruby")
# Model.tagged_with("hello", "world")
# Model.tagged_with("hello", "world", :limit => 10)
#
# XXX This query strategy is not performant, and needs to be rewritten as an inverted join or a series of unions
#
def tagged_with(*tag_list)
options = tag_list.last.is_a?(Hash) ? tag_list.pop : {}
tag_list = parse_tags(tag_list)
scope = scope(:find)
options[:select] ||= "#{table_name}.*"
options[:from] ||= "#{table_name}, tags, taggings"
sql = "SELECT #{(scope && scope[:select]) || options[:select]} "
sql << "FROM #{(scope && scope[:from]) || options[:from]} "
add_joins!(sql, options[:joins], scope)
sql << "WHERE #{table_name}.#{primary_key} = taggings.taggable_id "
sql << "AND taggings.taggable_type = '#{ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s}' "
sql << "AND taggings.tag_id = tags.id "
tag_list_condition = tag_list.map {|name| "'#{name}'"}.join(", ")
sql << "AND (tags.name IN (#{sanitize_sql(tag_list_condition)})) "
sql << "AND #{sanitize_sql(options[:conditions])} " if options[:conditions]
columns = column_names.map do |column|
"#{table_name}.#{column}"
end.join(", ")
sql << "GROUP BY #{columns} "
sql << "HAVING COUNT(taggings.tag_id) = #{tag_list.size}"
add_order!(sql, options[:order], scope)
add_limit!(sql, options, scope)
add_lock!(sql, options, scope)
find_by_sql(sql)
end
def self.tagged_with_any(*tag_list)
options = tag_list.last.is_a?(Hash) ? tag_list.pop : {}
tag_list = parse_tags(tag_list)
scope = scope(:find)
options[:select] ||= "#{table_name}.*"
options[:from] ||= "#{table_name}, meta_tags, taggings"
sql = "SELECT #{(scope && scope[:select]) || options[:select]} "
sql << "FROM #{(scope && scope[:from]) || options[:from]} "
add_joins!(sql, options, scope)
sql << "WHERE #{table_name}.#{primary_key} = taggings.taggable_id "
sql << "AND taggings.taggable_type = '#{ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s}' "
sql << "AND taggings.meta_tag_id = meta_tags.id "
sql << "AND ("
or_options = []
tag_list.each do |name|
or_options << "meta_tags.name = '#{name}'"
end
or_options_joined = or_options.join(" OR ")
sql << "#{or_options_joined}) "
sql << "AND #{sanitize_sql(options[:conditions])} " if options[:conditions]
columns = column_names.map do |column|
"#{table_name}.#{column}"
end.join(", ")
sql << "GROUP BY #{columns} "
add_order!(sql, options[:order], scope)
add_limit!(sql, options, scope)
add_lock!(sql, options, scope)
find_by_sql(sql)
end
def parse_tags(tags)
return [] if tags.blank?
tags = Array(tags).first
tags = tags.respond_to?(:flatten) ? tags.flatten : tags.split(Tag::DELIMITER)
tags.map { |tag| tag.strip.squeeze(" ") }.flatten.compact.map(&:downcase).uniq
end
end
include TaggingExtensions
extend TaggingFinders
end

View file

@ -0,0 +1,85 @@
require File.dirname(__FILE__) + '/../test_helper'
class TaggingTest < Test::Unit::TestCase
fixtures :tags, :taggings, <%= taggable_models[0..1].join(", ") -%>
def setup
@objs = <%= model_two %>.find(:all, :limit => 2)
@obj1 = @objs[0]
@obj1.tag_with("pale")
@obj1.reload
@obj2 = @objs[1]
@obj2.tag_with("pale imperial")
@obj2.reload
<% if taggable_models.size > 1 -%>
@obj3 = <%= model_one -%>.find(:first)
<% end -%>
@tag1 = Tag.find(1)
@tag2 = Tag.find(2)
@tagging1 = Tagging.find(1)
end
def test_tag_with
@obj2.tag_with "hoppy pilsner"
assert_equal "hoppy pilsner", @obj2.tag_list
end
def test_find_tagged_with
@obj1.tag_with "seasonal lager ipa"
@obj2.tag_with ["lager", "stout", "fruity", "seasonal"]
result1 = [@obj1]
assert_equal <%= model_two %>.tagged_with("ipa"), result1
assert_equal <%= model_two %>.tagged_with("ipa lager"), result1
assert_equal <%= model_two %>.tagged_with("ipa", "lager"), result1
result2 = [@obj1.id, @obj2.id].sort
assert_equal <%= model_two %>.tagged_with("seasonal").map(&:id).sort, result2
assert_equal <%= model_two %>.tagged_with("seasonal lager").map(&:id).sort, result2
assert_equal <%= model_two %>.tagged_with("seasonal", "lager").map(&:id).sort, result2
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 "longneck pale porter", @obj1.tag_list
@obj1._add_tags [2]
assert_equal "imperial longneck pale porter", @obj1.tag_list
end
def test__remove_tags
@obj2._remove_tags ["2", @tag1]
assert @obj2.tags.empty?
end
def test_tag_list
assert_equal "imperial pale", @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

View file

@ -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"

View file

@ -0,0 +1,7 @@
---
tags_001:
name: pale
id: "1"
tags_002:
name: imperial
id: "2"

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
require 'has_many_polymorphs'

View file

@ -0,0 +1,27 @@
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'] || ENV['RAILS_ENV'] =~ /development|test/ && 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/autoload'
end
_logger_debug "loaded ok"

View file

@ -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 <tt>has_many_polymorphs</tt> association.
class PolymorphicAssociation < HasManyThroughAssociation
# Push a record onto the association. Triggers a database load for a uniqueness check only if <tt>:skip_duplicates</tt> is <tt>true</tt>. 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 <tt>find</tt> against the association contents, returning the matched records. All regular <tt>find</tt> options except <tt>:include</tt> 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

View file

@ -0,0 +1,69 @@
require 'initializer' unless defined? ::Rails::Initializer
require 'action_controller/dispatcher' unless defined? ::ActionController::Dispatcher
module HasManyPolymorphs
=begin rdoc
Searches for models that use <tt>has_many_polymorphs</tt> or <tt>acts_as_double_polymorphic_join</tt> 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 <tt>after_initialize</tt> block in <tt>config/environment.rb</tt> that appends to the <tt>'requirements'</tt> 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
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)
# Dispatcher callback to load polymorphic relationships from the top down.
def self.autoload
_logger_debug "autoload hook invoked"
options[:requirements].each do |requirement|
_logger_warn "forcing requirement load of #{requirement}"
require requirement
end
Dir.glob(options[:file_pattern]).each do |filename|
next if filename =~ /#{options[:file_exclusions].join("|")}/
open filename do |file|
if file.grep(/#{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 "#{model} could not be preloaded: #{e.inspect}"
end
end
end
end
end
end
class Rails::Initializer #:nodoc:
# Make sure it gets loaded in the console, tests, and migrations
def after_initialize_with_autoload
after_initialize_without_autoload
HasManyPolymorphs.autoload
end
alias_method_chain :after_initialize, :autoload
end
ActionController::Dispatcher.to_prepare(:has_many_polymorphs_autoload) do
# Make sure it gets loaded in the app
HasManyPolymorphs.autoload
end

View file

@ -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

View file

@ -0,0 +1,600 @@
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 <tt>[:dogs, :cats]</tt>, and not <tt>[:animals]</tt>.
Namespaced models follow the Rails <tt>underscore</tt> convention. ZooAnimal::Lion becomes <tt>:'zoo_animal/lion'</tt>.
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 <tt>has_many_polymorphs</tt> 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, <tt>:eaters_extend</tt>.
<tt>:dependent</tt>:: Accepts <tt>:destroy</tt>, <tt>:nullify</tt>, or <tt>:delete_all</tt>. Controls how the join record gets treated on any association delete (whether from the polymorph or from an individual collection); defaults to <tt>:destroy</tt>.
<tt>:skip_duplicates</tt>:: If <tt>true</tt>, will check to avoid pushing already associated records (but also triggering a database load). Defaults to <tt>true</tt>.
<tt>:rename_individual_collections</tt>:: If <tt>true</tt>, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with <tt>"\_of_#{association_name}"</tt>.
<tt>:extend</tt>:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).
<tt>:join_extend</tt>:: One or an array of mixed modules and procs, which are applied to the join association.
<tt>:conditions</tt>:: An array or string of conditions for the SQL <tt>WHERE</tt> clause.
<tt>:order</tt>:: A string for the SQL <tt>ORDER BY</tt> clause.
<tt>:limit</tt>:: An integer. Affects the polymorphic and individual associations.
<tt>:offset</tt>:: An integer. Only affects the polymorphic association.
<tt>:namespace</tt>:: A symbol. Prepended to all the models in the <tt>:from</tt> and <tt>:through</tt> 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 <tt>:from</tt>.
The method generates a number of associations aside from the polymorphic one. In this example Petfood also gets <tt>dogs</tt>, <tt>cats</tt>, and <tt>birds</tt>, and Dog, Cat, and Bird get <tt>petfoods</tt>. (The reverse association to the parents is always plural.)
== Available options
<tt>:from</tt>:: An array of symbols representing the target models. Required.
<tt>:as</tt>:: A symbol for the parent's interface in the join--what the parent 'acts as'.
<tt>:through</tt>:: 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).
<tt>:dependent</tt>:: Accepts <tt>:destroy</tt>, <tt>:nullify</tt>, <tt>:delete_all</tt>. Controls how the join record gets treated on any associate delete (whether from the polymorph or from an individual collection); defaults to <tt>:destroy</tt>.
<tt>:skip_duplicates</tt>:: If <tt>true</tt>, will check to avoid pushing already associated records (but also triggering a database load). Defaults to <tt>true</tt>.
<tt>:rename_individual_collections</tt>:: If <tt>true</tt>, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with "_of_#{association_name}"</tt>. For example, <tt>zoos</tt> becomes <tt>zoos_of_animals</tt>. This is to help avoid method name collisions in crowded classes.
<tt>:extend</tt>:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).
<tt>:join_extend</tt>:: One or an array of mixed modules and procs, which are applied to the join association.
<tt>:parent_extend</tt>:: One or an array of mixed modules and procs, which are applied to the target models' association to the parents.
<tt>:conditions</tt>:: An array or string of conditions for the SQL <tt>WHERE</tt> clause.
<tt>:parent_conditions</tt>:: An array or string of conditions which are applied to the target models' association to the parents.
<tt>:order</tt>:: A string for the SQL <tt>ORDER BY</tt> clause.
<tt>:parent_order</tt>:: A string for the SQL <tt>ORDER BY</tt> which is applied to the target models' association to the parents.
<tt>:group</tt>:: An array or string of conditions for the SQL <tt>GROUP BY</tt> clause. Affects the polymorphic and individual associations.
<tt>:limit</tt>:: An integer. Affects the polymorphic and individual associations.
<tt>:offset</tt>:: An integer. Only affects the polymorphic association.
<tt>:namespace</tt>:: A symbol. Prepended to all the models in the <tt>:from</tt> and <tt>:through</tt> keys. This is especially useful for Camping, which namespaces models by default.
<tt>:uniq</tt>:: If <tt>true</tt>, the records returned are passed through a pure-Ruby <tt>uniq</tt> before they are returned. Rarely needed.
<tt>:foreign_key</tt>:: The column name for the parent's id in the join.
<tt>:foreign_type_key</tt>:: 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 <tt>acts_as_double_polymorphic_join()</tt> instead.
<tt>:polymorphic_key</tt>:: The column name for the child's id in the join.
<tt>:polymorphic_type_key</tt>:: 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 <tt>:extend</tt>.
== On condition nullification
When you request an individual association, non-applicable but fully-qualified fields in the polymorphic association's <tt>:conditions</tt>, <tt>:order</tt>, and <tt>:group</tt> options get changed to <tt>NULL</tt>. For example, if you set <tt>:conditions => "dogs.name != 'Spot'"</tt>, when you request <tt>.cats</tt>, the conditions string is changed to <tt>NULL != 'Spot'</tt>.
Be aware, however, that <tt>NULL != 'Spot'</tt> returns <tt>false</tt> due to SQL's 3-value logic. Instead, you need to use the <tt>:conditions</tt> string <tt>"dogs.name IS NULL OR dogs.name != 'Spot'"</tt> 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
create_reflection(:has_many_polymorphs, association_id, options, self).tap do |reflection|
# 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
{}.tap 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} (tried #{plural.to_s._classify}). If it's namespaced, be sure to specify it as :\"module/#{plural}\" instead."
end
begin
plural._as_class.columns.map(&:name).each_with_index do |field, f_index|
aliases["#{table}.#{field}"] = "t#{t_index}_r#{f_index}"
end
rescue ActiveRecord::StatementInvalid => e
_logger_warn "Looks like your table doesn't exist for #{plural.to_s._classify}.\nError #{e}\nSkipping..."
end
end
end
end
def build_select(association_id, aliases)
# <tt>instantiate</tt> 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
# 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

View file

@ -0,0 +1,19 @@
=begin rdoc
Access the <tt>has_many_polymorphs_options</tt> hash in your Rails::Initializer.run#after_initialize block if you need to modify the behavior of Rails::Initializer::HasManyPolymorphsAutoload.
=end
module Rails #:nodoc:
class Configuration
def has_many_polymorphs_options
::HasManyPolymorphs.options
end
def has_many_polymorphs_options=(hash)
::HasManyPolymorphs.options = HashWithIndifferentAccess.new(hash)
end
end
end

View file

@ -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 <tt>"ruby-debug"</tt>, <tt>"trace"</tt>, and <tt>"dependencies"</tt>.
== Code generation
Enabled by default when HMP_DEBUG is set.
Ouputs a folder <tt>generated_models/</tt> 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 <tt>"ruby-debug"</tt>.
Starts <tt>ruby-debug</tt> for the life of the process.
== Trace
Enable by setting HMP_DEBUG to <tt>"ruby-debug"</tt>.
Outputs an indented trace of relevant method calls as they occur.
== Dependencies
Enable by setting HMP_DEBUG to <tt>"dependencies"</tt>.
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

View file

@ -0,0 +1,35 @@
# 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
class Object
def silently
stderr, stdout, $stderr, $stdout = $stderr, $stdout, StringIO.new, StringIO.new
yield
$stderr, $stdout = stderr, stdout
end
end

View file

@ -0,0 +1,58 @@
module ActiveRecord #:nodoc:
module Reflection #:nodoc:
module ClassMethods #:nodoc:
# Update the default reflection switch so that <tt>:has_many_polymorphs</tt> 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
klass = options[:through] ? ThroughReflection : AssociationReflection
reflection = klass.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
write_inheritable_hash :reflections, name => reflection
reflection
end
end
class PolymorphicError < ActiveRecordError #:nodoc:
end
=begin rdoc
The reflection built by the <tt>has_many_polymorphs</tt> method.
Inherits from ActiveRecord::Reflection::AssociationReflection.
=end
class PolymorphicReflection < ThroughReflection
# 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

View file

@ -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

View file

@ -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"

View file

@ -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"

View file

@ -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"

View file

@ -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"

View file

@ -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"

View file

@ -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"

View file

@ -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"

View file

@ -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"

View file

@ -0,0 +1,42 @@
require 'fileutils'
require File.dirname(__FILE__) + '/../test_helper'
class TaggingGeneratorTest < Test::Unit::TestCase
def setup
Dir.chdir RAILS_ROOT do
truncate
# Revert environment lib requires
FileUtils.cp "config/environment.rb.canonical", "config/environment.rb"
# Delete generator output
["app/models/tag.rb", "app/models/tagging.rb",
"test/unit/tag_test.rb", "test/unit/tagging_test.rb",
"test/fixtures/tags.yml", "test/fixtures/taggings.yml",
"lib/tagging_extensions.rb",
"db/migrate/010_create_tags_and_taggings.rb"].each do |file|
File.delete file if File.exist? file
end
# Rebuild database
Echoe.silence do
system("ruby #{HERE}/setup.rb")
end
end
end
alias :teardown :setup
def test_generator
Dir.chdir RAILS_ROOT do
Echoe.silence do
assert system("script/generate tagging Stick Stone -q -f")
assert system("rake db:migrate")
assert system("rake db:fixtures:load")
assert system("rake test:units")
end
end
end
end

View file

@ -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: <tt>script/server</tt> (run with --help for options)
3. Go to http://localhost:3000/ and get "Welcome aboard: Youre 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: <tt>gem install mongrel</tt>.
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
=> "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
#<Post:0x14a6620 @attributes={\"title\"=>\"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
=> #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
>> f.
Display all 152 possibilities? (y or n)
Finally, when you're ready to resume execution, you press CTRL-D
== Console
You can interact with the domain model by starting the console through <tt>script/console</tt>.
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 <tt>script/console production</tt>.
To reload your controllers and models after launching the console run <tt>reload!</tt>
To reload your controllers and models after launching the console run <tt>reload!</tt>
== 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
<tt>layout :default</tt> 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 <tt>rake doc:app</tt>
lib
Application specific libraries. Basically, any kind of custom code that doesn't
belong under controllers, models, or helpers. This directory is in the load path.
public
The directory available for the web server. Contains subdirectories for images, stylesheets,
and javascripts. Also contains the dispatchers and the default HTML files. This should be
set as the DOCUMENT_ROOT of your web server.
script
Helper scripts for automation and generation.
test
Unit and functional tests along with fixtures. When using the 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.

View file

@ -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

View file

@ -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

View file

@ -0,0 +1,5 @@
class BonesController < ApplicationController
def index
@bones = Bone.find(:all)
end
end

View file

@ -0,0 +1,2 @@
module AddressesHelper
end

View file

@ -0,0 +1,3 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
end

View file

@ -0,0 +1,2 @@
module BonesHelper
end

View file

@ -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

View file

@ -0,0 +1,2 @@
module StatesHelper
end

View file

@ -0,0 +1,2 @@
module UsersHelper
end

View file

@ -0,0 +1,2 @@
class Bone < OrganicSubstance
end

View file

@ -0,0 +1,2 @@
class DoubleStiParent < ActiveRecord::Base
end

View file

@ -0,0 +1,2 @@
class DoubleStiParentRelationship < ActiveRecord::Base
end

View file

@ -0,0 +1,2 @@
class OrganicSubstance < ActiveRecord::Base
end

View file

@ -0,0 +1,4 @@
class SingleStiParent < ActiveRecord::Base
has_many_polymorphs :the_bones, :from => [:bones], :through => :single_sti_parent_relationship
end

View file

@ -0,0 +1,4 @@
class SingleStiParentRelationship < ActiveRecord::Base
belongs_to :single_sti_parent
belongs_to :the_bone, :polymorphic => true
end

View file

@ -0,0 +1,2 @@
class Stick < ActiveRecord::Base
end

View file

@ -0,0 +1,2 @@
class Stone < ActiveRecord::Base
end

View file

@ -0,0 +1,12 @@
<h1>Editing address</h1>
<%= error_messages_for :address %>
<% form_for(@address) do |f| %>
<p>
<%= f.submit "Update" %>
</p>
<% end %>
<%= link_to 'Show', @address %> |
<%= link_to 'Back', addresses_path %>

View file

@ -0,0 +1,18 @@
<h1>Listing addresses</h1>
<table>
<tr>
</tr>
<% for address in @addresses %>
<tr>
<td><%= link_to 'Show', address %></td>
<td><%= link_to 'Edit', edit_address_path(address) %></td>
<td><%= link_to 'Destroy', address, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New address', new_address_path %>

View file

@ -0,0 +1,11 @@
<h1>New address</h1>
<%= error_messages_for :address %>
<% form_for(@address) do |f| %>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
<%= link_to 'Back', addresses_path %>

View file

@ -0,0 +1,3 @@
<%= link_to 'Edit', edit_address_path(@address) %> |
<%= link_to 'Back', addresses_path %>

View file

@ -0,0 +1,5 @@
<p>Bones: index</p>
<% @bones.each do |bone| %>
<p>ID: <%= bone.id %></p>
<% end %>

View file

@ -0,0 +1,17 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Addresses: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold' %>
</head>
<body>
<p style="color: green"><%= flash[:notice] %></p>
<%= yield %>
</body>
</html>

View file

@ -0,0 +1,17 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Sellers: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold' %>
</head>
<body>
<p style="color: green"><%= flash[:notice] %></p>
<%= yield %>
</body>
</html>

View file

@ -0,0 +1,17 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>States: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold' %>
</head>
<body>
<p style="color: green"><%= flash[:notice] %></p>
<%= yield %>
</body>
</html>

View file

@ -0,0 +1,17 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Users: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold' %>
</head>
<body>
<p style="color: green"><%= flash[:notice] %></p>
<%= yield %>
</body>
</html>

View file

@ -0,0 +1,12 @@
<h1>Editing seller</h1>
<%= error_messages_for :seller %>
<% form_for(@seller) do |f| %>
<p>
<%= f.submit "Update" %>
</p>
<% end %>
<%= link_to 'Show', @seller %> |
<%= link_to 'Back', sellers_path %>

View file

@ -0,0 +1,20 @@
<h1>Listing sellers</h1>
<table>
<tr>
</tr>
<% for seller in @sellers %>
<tr>
<td><%= h(seller.company_name) %></td>
<td><%= h(display_address(seller)) %></td>
<td><%= link_to 'Show', seller %></td>
<td><%= link_to 'Edit', edit_seller_path(seller) %></td>
<td><%= link_to 'Destroy', seller, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New seller', new_seller_path %>

View file

@ -0,0 +1,11 @@
<h1>New seller</h1>
<%= error_messages_for :seller %>
<% form_for(@seller) do |f| %>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
<%= link_to 'Back', sellers_path %>

View file

@ -0,0 +1,3 @@
<%= link_to 'Edit', edit_seller_path(@seller) %> |
<%= link_to 'Back', sellers_path %>

View file

@ -0,0 +1,12 @@
<h1>Editing state</h1>
<%= error_messages_for :state %>
<% form_for(@state) do |f| %>
<p>
<%= f.submit "Update" %>
</p>
<% end %>
<%= link_to 'Show', @state %> |
<%= link_to 'Back', states_path %>

View file

@ -0,0 +1,19 @@
<h1>Listing states</h1>
<table>
<tr>
</tr>
<% for state in @states %>
<tr>
<td><%= state.name %></td>
<td><%= link_to 'Show', state %></td>
<td><%= link_to 'Edit', edit_state_path(state) %></td>
<td><%= link_to 'Destroy', state, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New state', new_state_path %>

View file

@ -0,0 +1,11 @@
<h1>New state</h1>
<%= error_messages_for :state %>
<% form_for(@state) do |f| %>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
<%= link_to 'Back', states_path %>

View file

@ -0,0 +1,3 @@
<%= link_to 'Edit', edit_state_path(@state) %> |
<%= link_to 'Back', states_path %>

View file

@ -0,0 +1,12 @@
<h1>Editing user</h1>
<%= error_messages_for :user %>
<% form_for(@user) do |f| %>
<p>
<%= f.submit "Update" %>
</p>
<% end %>
<%= link_to 'Show', @user %> |
<%= link_to 'Back', users_path %>

View file

@ -0,0 +1,22 @@
<h1>Listing users</h1>
<table>
<tr>
</tr>
<% for user in @users %>
<tr>
<td><%= h(user.login) %></td>
<td><%= h(user.address.line_1) %></td>
<td><%= h(user.address.city) %></td>
<td><%= h(user.address.state.name) %></td>
<td><%= link_to 'Show', user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<td><%= link_to 'Destroy', user, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New user', new_user_path %>

View file

@ -0,0 +1,11 @@
<h1>New user</h1>
<%= error_messages_for :user %>
<% form_for(@user) do |f| %>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
<%= link_to 'Back', users_path %>

View file

@ -0,0 +1,3 @@
<%= link_to 'Edit', edit_user_path(@user) %> |
<%= link_to 'Back', users_path %>

View file

@ -0,0 +1,110 @@
# Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
module Rails
class << self
def boot!
unless booted?
preinitialize
pick_boot.run
end
end
def booted?
defined? Rails::Initializer
end
def pick_boot
(vendor_rails? ? VendorBoot : GemBoot).new
end
def vendor_rails?
File.exist?("#{RAILS_ROOT}/vendor/rails")
end
def preinitialize
load(preinitializer_path) if File.exists?(preinitializer_path)
end
def preinitializer_path
"#{RAILS_ROOT}/config/preinitializer.rb"
end
end
class Boot
def run
load_initializer
Rails::Initializer.run(:set_load_path)
end
end
class VendorBoot < Boot
def load_initializer
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
end
end
class GemBoot < Boot
def load_initializer
self.class.load_rubygems
load_rails_gem
require 'initializer'
end
def load_rails_gem
if version = self.class.gem_version
STDERR.puts "Boot.rb loading version #{version}"
gem 'rails', version
else
STDERR.puts "Boot.rb loading latest available version"
gem 'rails'
end
rescue Gem::LoadError => load_error
$stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
exit 1
end
class << self
def rubygems_version
Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion
end
def gem_version
if defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION
elsif ENV.include?('RAILS_GEM_VERSION')
ENV['RAILS_GEM_VERSION']
else
parse_gem_version(read_environment_rb)
end
end
def load_rubygems
require 'rubygems'
unless rubygems_version >= '0.9.4'
$stderr.puts %(Rails requires RubyGems >= 0.9.4 (you have #{rubygems_version}). Please `gem update --system` and try again.)
exit 1
end
rescue LoadError
$stderr.puts %(Rails requires RubyGems >= 0.9.4. Please install RubyGems and try again: http://rubygems.rubyforge.org)
exit 1
end
def parse_gem_version(text)
$1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*'([!~<>=]*\s*[\d.]+)'/
end
private
def read_environment_rb
File.read("#{RAILS_ROOT}/config/environment.rb")
end
end
end
end
# All that for this:
Rails.boot!

View file

@ -0,0 +1,17 @@
defaults: &defaults
adapter: <%= ENV['DB'] || 'mysql' %>
host: localhost
database: hmp_development
username: root
password:
development:
<<: *defaults
test:
<<: *defaults
production:
<<: *defaults

View file

@ -0,0 +1,19 @@
require File.join(File.dirname(__FILE__), 'boot')
require 'action_controller'
Rails::Initializer.run do |config|
if ActionController::Base.respond_to? 'session='
config.action_controller.session = {:session_key => '_app_session', :secret => '22cde4d5c1a61ba69a81795322cde4d5c1a61ba69a817953'}
end
config.load_paths << "#{RAILS_ROOT}/app/models/person" # moduleless model path
config.after_initialize do
config.has_many_polymorphs_options['requirements'] << "#{RAILS_ROOT}/lib/library_model"
end
end
# Dependencies.log_activity = true
ENV['RAILS_ASSET_ID'] = Time.now.to_i.to_s

View file

@ -0,0 +1,19 @@
require File.join(File.dirname(__FILE__), 'boot')
require 'action_controller'
Rails::Initializer.run do |config|
if ActionController::Base.respond_to? 'session='
config.action_controller.session = {:session_key => '_app_session', :secret => '22cde4d5c1a61ba69a81795322cde4d5c1a61ba69a817953'}
end
config.load_paths << "#{RAILS_ROOT}/app/models/person" # moduleless model path
config.after_initialize do
config.has_many_polymorphs_options['requirements'] << "#{RAILS_ROOT}/lib/library_model"
end
end
# Dependencies.log_activity = true
ENV['RAILS_ASSET_ID'] = Time.now.to_i.to_s

View file

@ -0,0 +1,9 @@
config.cache_classes = ENV['PRODUCTION']
config.whiny_nils = true
config.action_controller.consider_all_requests_local = !ENV['PRODUCTION']
config.action_controller.perform_caching = ENV['PRODUCTION']
# The following has been deprecated in Rails 2.1 and removed in 2.2
config.action_view.cache_template_extensions = ENV['PRODUCTION'] if Rails::VERSION::MAJOR < 2 or Rails::VERSION::MAJOR == 2 && Rails::VERSION::MINOR < 1
config.action_view.debug_rjs = !ENV['PRODUCTION']
config.action_mailer.raise_delivery_errors = false

View file

@ -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

View file

@ -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

View file

@ -0,0 +1,6 @@
---
mode: development
runs_at_launch: 0
identifier: testapp
port: 3005
bundle: /Applications/Locomotive2/Bundles/rmagickRailsMar2007_i386.locobundle

View file

@ -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

View file

@ -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,
}

View file

@ -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
}

View file

@ -0,0 +1,11 @@
class CreateSticks < ActiveRecord::Migration
def self.up
create_table :sticks do |t|
t.column :name, :string
end
end
def self.down
drop_table :sticks
end
end

View file

@ -0,0 +1,11 @@
class CreateStones < ActiveRecord::Migration
def self.up
create_table :stones do |t|
t.column :name, :string
end
end
def self.down
drop_table :stones
end
end

View file

@ -0,0 +1,11 @@
class CreateOrganicSubstances < ActiveRecord::Migration
def self.up
create_table :organic_substances do |t|
t.column :type, :string
end
end
def self.down
drop_table :organic_substances
end
end

View file

@ -0,0 +1,8 @@
class CreateBones < ActiveRecord::Migration
def self.up
# Using STI
end
def self.down
end
end

View file

@ -0,0 +1,11 @@
class CreateSingleStiParents < ActiveRecord::Migration
def self.up
create_table :single_sti_parents do |t|
t.column :name, :string
end
end
def self.down
drop_table :single_sti_parents
end
end

View file

@ -0,0 +1,11 @@
class CreateDoubleStiParents < ActiveRecord::Migration
def self.up
create_table :double_sti_parents do |t|
t.column :name, :string
end
end
def self.down
drop_table :double_sti_parents
end
end

View file

@ -0,0 +1,13 @@
class CreateSingleStiParentRelationships < ActiveRecord::Migration
def self.up
create_table :single_sti_parent_relationships do |t|
t.column :the_bone_type, :string, :null => false
t.column :the_bone_id, :integer, :null => false
t.column :single_sti_parent_id, :integer, :null => false
end
end
def self.down
drop_table :single_sti_parent_relationships
end
end

Some files were not shown because too many files have changed in this diff Show more