public
Rubygem
Description: Dynamically generates aliases for polymorphic associations based on the class names of those associations
Homepage: http://www.pluginaweek.org
Clone URL: git://github.com/pluginaweek/polymorphic_identity.git
name age message
file .gitignore Fri Jul 04 15:49:01 -0700 2008 Ignore test/app_root/script [obrie]
file CHANGELOG.rdoc Sun Dec 14 19:28:13 -0800 2008 Tag 0.1.0 release [obrie]
file LICENSE Loading commit data...
file README.rdoc Mon Apr 13 18:52:11 -0700 2009 Minor doc / formatting tweaks [obrie]
file Rakefile
file init.rb Fri Feb 09 15:10:38 -0800 2007 Initial revision. [obrie]
directory lib/ Sun Dec 14 19:26:55 -0800 2008 Remove the PluginAWeek namespace [obrie]
file polymorphic_identity.gemspec
directory test/ Mon Apr 13 18:52:11 -0700 2009 Minor doc / formatting tweaks [obrie]

polymorphic_identity

polymorphic_identity dynamically generates aliases for polymorphic associations based on the class names of those associations.

Resources

API

Bugs

Development

Source

  • git://github.com/pluginaweek/polymorphic_identity.git

Description

Polymorphic associations are not very descriptive when it comes to easily knowing the type of model your interacting with. For example, a typical polymorphic assocation looks like the following:

  class Tag < ActiveRecord::Base
    belongs_to :taggable, :polymorphic => true
  end

When getting the taggable record, you would normally have to call tag.taggable. However, if you know that the taggable record is just an instance of the Article model, then it would feel more comfortable if you could just call tag.article. polymoprhic_identity makes this possible by dynamically checking the name of the polymorphic record’s class and creating methods that allow you to access the polymorphic association based on that class name.

Usage

Example

  class Comment < ActiveRecord::Base
    belongs_to :commentable, :polymorphic => true
    belongs_to :commenter, :polymorphic => true
  end

  class Article < ActiveRecord::Base
    has_many :comments, :as => :commentable
  end

  class User < ActiveRecord::Base
    has_many :comments, :as => :commenter
  end

  c = Comment.find(1)   # => #<Tag id: 1, commentable_id: 1, commentable_type: "Article", commenter_id: 1, commenter_type: "User"}>
  c.commentable         # => #<Article id: 1>
  c.article             # => #<Article id: 1>
  c.commenter           # => #<User id: 1>
  c.user                # => #<User id: 1>

Testing

Before you can run any tests, the following gem must be installed:

To run against a specific version of Rails:

  rake test RAILS_FRAMEWORK_ROOT=/path/to/rails

Dependencies

  • Rails 2.0 or later