Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Initial revision.

  • Loading branch information...
commit 430774972fccef5501c68de5b86f359d7cecc642 0 parents
@obrie obrie authored
Showing with 456 additions and 0 deletions.
  1. +2 −0  CHANGELOG
  2. +20 −0 MIT-LICENSE
  3. +24 −0 README
  4. +80 −0 Rakefile
  5. +1 −0  init.rb
  6. +35 −0 lib/polymorphic_identity.rb
  7. +4 −0 test/app_root/app/models/article.rb
  8. +4 −0 test/app_root/app/models/author.rb
  9. +6 −0 test/app_root/app/models/comment.rb
  10. +4 −0 test/app_root/app/models/page.rb
  11. +4 −0 test/app_root/app/models/user.rb
  12. +13 −0 test/app_root/config/boot.rb
  13. +22 −0 test/app_root/config/database.yml
  14. +45 −0 test/app_root/config/environment.rb
  15. +11 −0 test/app_root/db/migrate/001_create_authors.rb
  16. +12 −0 test/app_root/db/migrate/002_create_articles.rb
  17. +12 −0 test/app_root/db/migrate/003_create_pages.rb
  18. +11 −0 test/app_root/db/migrate/004_create_users.rb
  19. +14 −0 test/app_root/db/migrate/005_create_comments.rb
  20. +9 −0 test/app_root/test/fixtures/articles.yml
  21. +7 −0 test/app_root/test/fixtures/authors.yml
  22. +25 −0 test/app_root/test/fixtures/comments.yml
  23. +9 −0 test/app_root/test/fixtures/pages.yml
  24. +7 −0 test/app_root/test/fixtures/users.yml
  25. +31 −0 test/test_helper.rb
  26. +44 −0 test/unit/polymorphic_identity_test.rb
2  CHANGELOG
@@ -0,0 +1,2 @@
+*SVN*
+
20 MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2005-2006 Aaron Pfeifer & Neil Abraham
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 README
@@ -0,0 +1,24 @@
+= polymorphic_identity
+
+polymorphic_identity .
+
+== Resources
+
+Wiki
+
+* http://wiki.pluginaweek.org/Polymorphic_Identity
+
+Announcement
+
+* http://www.pluginaweek.org/
+
+Source
+
+* http://svn.pluginaweek.org/trunk/plugins/active_record/associations/polymorphic_identity
+
+Development
+
+* http://dev.pluginaweek.org/browser/trunk/plugins/active_record/associations/polymorphic_identity
+
+== Description
+
80 Rakefile
@@ -0,0 +1,80 @@
+require 'rake/testtask'
+require 'rake/rdoctask'
+require 'rake/gempackagetask'
+require 'rake/contrib/sshpublisher'
+
+PKG_NAME = 'polymorphic_identity'
+PKG_VERSION = '0.0.1'
+PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}"
+RUBY_FORGE_PROJECT = 'pluginaweek'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the polymorphic_identity plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.pattern = 'test/unit/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for the polymorphic_identity plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'ClassAssociations'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
+
+spec = Gem::Specification.new do |s|
+ s.name = PKG_NAME
+ s.version = PKG_VERSION
+ s.platform = Gem::Platform::RUBY
+ s.summary = ''
+
+ s.files = FileList['{lib,tasks,test}/**/*'].to_a + %w(init.rb MIT-LICENSE Rakefile README)
+ s.require_path = 'lib'
+ s.autorequire = 'polymorphic_identity'
+ s.has_rdoc = true
+ s.test_files = Dir['test/unit/**/*_test.rb']
+ s.add_dependency 'activerecord', '>= 1.15.0'
+
+ s.author = 'Aaron Pfeifer and Neil Abraham'
+ s.email = 'info@pluginaweek.org'
+ s.homepage = 'http://www.pluginaweek.org'
+end
+
+Rake::GemPackageTask.new(spec) do |p|
+ p.gem_spec = spec
+ p.need_tar = true
+ p.need_zip = true
+end
+
+desc 'Publish the beta gem'
+task :pgem => [:package] do
+ Rake::SshFilePublisher.new('pluginaweek@pluginaweek.org', '/home/pluginaweek/gems.pluginaweek.org/gems', 'pkg', "#{PKG_FILE_NAME}.gem").upload
+end
+
+desc 'Publish the API documentation'
+task :pdoc => [:rdoc] do
+ Rake::SshDirPublisher.new('pluginaweek@pluginaweek.org', "/home/pluginaweek/api.pluginaweek.org/#{PKG_NAME}", 'rdoc').upload
+end
+
+desc 'Publish the API docs and gem'
+task :publish => [:pdoc, :release]
+
+desc 'Publish the release files to RubyForge.'
+task :release => [:gem, :package] do
+ require 'rubyforge'
+
+ ruby_forge = RubyForge.new
+ ruby_forge.login
+
+ %w( gem tgz zip ).each do |ext|
+ file = "pkg/#{PKG_FILE_NAME}.#{ext}"
+ puts "Releasing #{File.basename(file)}..."
+
+ ruby_forge.add_release(RUBY_FORGE_PROJECT, PKG_NAME, PKG_VERSION, file)
+ end
+end
1  init.rb
@@ -0,0 +1 @@
+require 'polymorphic_identity'
35 lib/polymorphic_identity.rb
@@ -0,0 +1,35 @@
+module PluginAWeek
+ #
+ module PolymorphicIdentity
+ def self.included(base)
+ base.class_eval do
+ alias_method_chain :method_missing, :polymorphic_identity
+ alias_method_chain :respond_to?, :polymorphic_identity
+ end
+ end
+
+ def method_missing_with_polymorphic_identity(method_id, *args, &block) #:nodoc:
+ polymorphic_reflection = self.class.reflections.values.find do |reflection|
+ reflection.options[:polymorphic] && read_attribute(reflection.options[:foreign_type]) == method_id.to_s.camelize
+ end
+
+ if polymorphic_reflection
+ send(polymorphic_reflection.name, *args, &block)
+ else
+ method_missing_witouth_polymorphic_identity(method_id, *args, &block)
+ end
+ end
+
+ def respond_to_with_polymorphic_identity?(method, include_priv = false) #:nodoc:
+ return true if respond_to_without_polymorphic_identity?(method, include_priv)
+
+ self.class.reflections.values.detect do |reflection|
+ reflection.options[:polymorphic] && read_attribute(reflection.options[:foreign_type]) == method.to_s.camelize
+ end
+ end
+ end
+end
+
+ActiveRecord::Base.class_eval do
+ include PluginAWeek::PolymorphicIdentity
+end
4 test/app_root/app/models/article.rb
@@ -0,0 +1,4 @@
+class Article < ActiveRecord::Base
+ has_many :comments,
+ :as => :commentable
+end
4 test/app_root/app/models/author.rb
@@ -0,0 +1,4 @@
+class Author < ActiveRecord::Base
+ has_many :comments,
+ :as => :commenter
+end
6 test/app_root/app/models/comment.rb
@@ -0,0 +1,6 @@
+class Comment < ActiveRecord::Base
+ belongs_to :commentable,
+ :polymorphic => true
+ belongs_to :commenter,
+ :polymorphic => true
+end
4 test/app_root/app/models/page.rb
@@ -0,0 +1,4 @@
+class Page < ActiveRecord::Base
+ has_many :comments,
+ :as => :commentable
+end
4 test/app_root/app/models/user.rb
@@ -0,0 +1,4 @@
+class User < ActiveRecord::Base
+ has_many :comments,
+ :as => :commenter
+end
13 test/app_root/config/boot.rb
@@ -0,0 +1,13 @@
+unless defined?(APP_ROOT)
+ root_path = File.join(File.dirname(__FILE__), '..')
+
+ unless RUBY_PLATFORM =~ /mswin32/
+ require 'pathname'
+ root_path = Pathname.new(root_path).cleanpath(true).to_s
+ end
+
+ APP_ROOT = root_path
+end
+
+require 'rubygems'
+require 'active_record'
22 test/app_root/config/database.yml
@@ -0,0 +1,22 @@
+in_memory:
+ adapter: sqlite3
+ database: ":memory:"
+ verbosity: quiet
+sqlite:
+ adapter: sqlite
+ dbfile: polymorphic_identity_test.sqlite.db
+sqlite3:
+ adapter: sqlite3
+ dbfile: polymorphic_identity_test.sqlite3.db
+postgresql:
+ adapter: postgresql
+ username: postgres
+ password: postgres
+ database: polymorphic_identity_test
+ min_messages: ERROR
+mysql:
+ adapter: mysql
+ host: localhost
+ username: root
+ password:
+ database: polymorphic_identity_test
45 test/app_root/config/environment.rb
@@ -0,0 +1,45 @@
+require File.join(File.dirname(__FILE__), 'boot')
+
+# set_load_path
+load_paths = %w(app app/models config vendor).collect {|dir| "#{APP_ROOT}/#{dir}"}
+load_paths.reverse_each {|dir| $LOAD_PATH.unshift("#{APP_ROOT}/#{dir}") if File.directory?(dir)}
+$LOAD_PATH.uniq!
+
+# set_autoload_paths
+Dependencies.load_paths = load_paths
+
+# load_environment
+APP_ENV = ENV['DB']
+
+# initialize_database
+ActiveRecord::Base.configurations = YAML::load(IO.read("#{APP_ROOT}/config/database.yml"))
+ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[APP_ENV])
+
+# initializer_logger
+log_path = "#{APP_ROOT}/log/#{APP_ENV}.log"
+begin
+ logger = Logger.new(log_path)
+ logger.level = Logger::DEBUG
+rescue StandardError
+ logger = Logger.new(STDERR)
+ logger.level = Logger::WARN
+ logger.warn(
+ "Logger Error: Unable to access log file. Please ensure that #{log_path} exists and is chmod 0666. " +
+ "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
+ )
+end
+
+# initialize_framework_logging
+ActiveRecord::Base.logger = logger
+
+# initialize_dependency_mechanism
+Dependencies.mechanism = :require
+
+# initialize_breakpoints
+require 'active_support/breakpoint'
+
+# initialize_whiny_nils
+# require('active_support/whiny_nil')
+
+# load_observers
+ActiveRecord::Base.instantiate_observers
11 test/app_root/db/migrate/001_create_authors.rb
@@ -0,0 +1,11 @@
+class CreateAuthors < ActiveRecord::Migration
+ def self.up
+ create_table :authors do |t|
+ t.column :name, :string
+ end
+ end
+
+ def self.down
+ drop_table :authors
+ end
+end
12 test/app_root/db/migrate/002_create_articles.rb
@@ -0,0 +1,12 @@
+class CreateArticles < ActiveRecord::Migration
+ def self.up
+ create_table :articles do |t|
+ t.column :author_id, :integer
+ t.column :content, :text
+ end
+ end
+
+ def self.down
+ drop_table :articles
+ end
+end
12 test/app_root/db/migrate/003_create_pages.rb
@@ -0,0 +1,12 @@
+class CreatePages < ActiveRecord::Migration
+ def self.up
+ create_table :pages do |t|
+ t.column :author_id, :integer
+ t.column :content, :text
+ end
+ end
+
+ def self.down
+ drop_table :pages
+ end
+end
11 test/app_root/db/migrate/004_create_users.rb
@@ -0,0 +1,11 @@
+class CreateUsers < ActiveRecord::Migration
+ def self.up
+ create_table :users do |t|
+ t.column :name, :string
+ end
+ end
+
+ def self.down
+ drop_table :users
+ end
+end
14 test/app_root/db/migrate/005_create_comments.rb
@@ -0,0 +1,14 @@
+class CreateComments < ActiveRecord::Migration
+ def self.up
+ create_table :comments do |t|
+ t.column :commentable_id, :integer
+ t.column :commentable_type, :string
+ t.column :commenter_id, :string
+ t.column :commenter_type, :string
+ end
+ end
+
+ def self.down
+ drop_table :comments
+ end
+end
9 test/app_root/test/fixtures/articles.yml
@@ -0,0 +1,9 @@
+test:
+ id: 1
+ author_id: 1
+ content: This is a test of the Emergency Broadcast System. If this had been an actual emergency...
+
+welcome:
+ id: 2
+ author_id: 2
+ content: Welcome!
7 test/app_root/test/fixtures/authors.yml
@@ -0,0 +1,7 @@
+john_doe:
+ id: 1
+ name: John Doe
+
+jane_doe:
+ id: 2
+ name: Jane Doe
25 test/app_root/test/fixtures/comments.yml
@@ -0,0 +1,25 @@
+<%
+id = 0
+[
+ [:article, :test, 1],
+ [:article, :welcome, 2],
+ [:page, :about, 1],
+ [:page, :projects, 2]
+].each do |commentable_type, commentable_name, commentable_id|
+ [
+ [:author, :john_doe, 1],
+ [:author, :jane_doe, 2],
+ [:user, :anonymous, 1],
+ [:user, :registered, 2]
+ ].each do |commenter_type, commenter_name, commenter_id|
+%>
+<%= commentable_type %>_<%= commentable_name %>_<%= commenter_type %>_<%= commenter_name %>:
+ id: <%= id += 1 %>
+ commentable_id: <%= commentable_id %>
+ commentable_type: <%= commentable_type.to_s.camelize %>
+ commenter_id: <%= commenter_id %>
+ commenter_type: <%= commenter_type.to_s.camelize %>
+<%
+ end
+end
+%>
9 test/app_root/test/fixtures/pages.yml
@@ -0,0 +1,9 @@
+about:
+ id: 1
+ author_id: 1
+ content: A little section about us
+
+projects:
+ id: 2
+ author_id: 2
+ content: A little section about the projects we do
7 test/app_root/test/fixtures/users.yml
@@ -0,0 +1,7 @@
+anonymous:
+ id: 1
+ name: Anonymous
+
+registered:
+ id: 2
+ name: Registered
31 test/test_helper.rb
@@ -0,0 +1,31 @@
+# Load the environment
+ENV['DB'] ||= 'in_memory'
+require File.dirname(__FILE__) + '/app_root/config/environment.rb'
+
+# Load the testing framework
+require 'test/unit'
+require 'active_record/fixtures'
+
+# Load the plugin
+$:.unshift(File.dirname(__FILE__) + '/../lib')
+require File.dirname(__FILE__) + '/../init'
+
+# Run the migrations
+ActiveRecord::Migrator.migrate("#{APP_ROOT}/db/migrate")
+
+# Load fixtures
+Test::Unit::TestCase.fixture_path = "#{APP_ROOT}/test/fixtures/"
+$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path)
+
+class Test::Unit::TestCase #:nodoc:
+ def create_fixtures(*table_names)
+ if block_given?
+ Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) { yield }
+ else
+ Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names)
+ end
+ end
+
+ self.use_transactional_fixtures = true
+ self.use_instantiated_fixtures = false
+end
44 test/unit/polymorphic_identity_test.rb
@@ -0,0 +1,44 @@
+require File.dirname(__FILE__) + '/../test_helper'
+
+class PolymorphicIdentityTest < Test::Unit::TestCase
+ fixtures :authors, :articles, :pages, :users, :comments
+
+ def test_no_value
+ ([Comment.new] + Comment.find(:all)).each do |c|
+ c.commentable = nil if c.commentable
+ c.commenter = nil if c.commenter
+
+ assert !c.respond_to?(:article)
+ assert !c.respond_to?(:page)
+ assert !c.respond_to?(:author)
+ assert !c.respond_to?(:user)
+ end
+ end
+
+ def test_existing_value
+ c = comments(:article_test_author_john_doe)
+ assert c.respond_to?(:article)
+ assert c.respond_to?(:author)
+ assert_equal articles(:test), c.article
+ assert_equal authors(:john_doe), c.author
+
+ c = comments(:page_about_user_anonymous)
+ assert c.respond_to?(:page)
+ assert c.respond_to?(:user)
+ assert_equal pages(:about), c.page
+ assert_equal users(:anonymous), c.user
+ end
+
+ def test_change_value
+ c = comments(:article_test_author_john_doe)
+ c.commentable = pages(:about)
+ c.commenter = users(:anonymous)
+
+ assert !c.respond_to?(:article)
+ assert !c.respond_to?(:author)
+ assert c.respond_to?(:page)
+ assert c.respond_to?(:user)
+ assert_equal pages(:about), c.page
+ assert_equal users(:anonymous), c.user
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.