Module: PolymorphicIdentity
- Defined in:
- lib/polymorphic_identity.rb
Overview
Adds dynamic attributes for polymorphic associations based on the name of the class for the polymorphic record. For example,
class Tag < ActiveRecord::Base
belongs_to :taggable, :polymorphic => true
end
class Article < ActiveRecord::Base
has_many :tags, :as => :taggable
end
t = Tag.find(1) # => #<Tag id: 1, taggable_id: 1, taggable_type: "Article">
t.taggable # => #<Article id: 1>
t.article # => #<Article id: 1>
Class Method Summary collapse
-
.included(base) ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#method_missing_with_polymorphic_identity(method_id, *args, &block) ⇒ Object
:nodoc:.
-
#respond_to_with_polymorphic_identity?(method, include_priv = false) ⇒ Boolean
True if a polymorphic association can be found whose foreign type is set to the name of the method.
Class Method Details
.included(base) ⇒ Object
:nodoc:
16 17 18 19 20 21 |
# File 'lib/polymorphic_identity.rb', line 16 def self.included(base) #:nodoc: base.class_eval do alias_method_chain :method_missing, :polymorphic_identity alias_method_chain :respond_to?, :polymorphic_identity end end |
Instance Method Details
#method_missing_with_polymorphic_identity(method_id, *args, &block) ⇒ Object
:nodoc:
23 24 25 26 27 28 29 |
# File 'lib/polymorphic_identity.rb', line 23 def method_missing_with_polymorphic_identity(method_id, *args, &block) #:nodoc: if association_name = find_polymorphic_association_name(method_id) send(association_name, *args, &block) else method_missing_without_polymorphic_identity(method_id, *args, &block) end end |
#respond_to_with_polymorphic_identity?(method, include_priv = false) ⇒ Boolean
True if a polymorphic association can be found whose foreign type is set to the name of the method
33 34 35 |
# File 'lib/polymorphic_identity.rb', line 33 def respond_to_with_polymorphic_identity?(method, include_priv = false) #:nodoc: respond_to_without_polymorphic_identity?(method, include_priv) || !find_polymorphic_association_name(method).nil? end |