Module: DataMapper::Address::Polymorphic

Defined in:
lib/dm-address/polymorphic.rb

Overview

Add fields to an Address class (such as one that includes Address::US) to allow for roughly polymorphic associations, belonging to other classes. (See pastie.org/214893). Including this module adds two properties: addressable_class and addressable_id, and one method, addressable, for accessing the parent record.

To use (in Address class):

include DataMapper::Address::Polymorphic

In parent class, something along the lines of:

has n, :addresses, :class_name => 'Address',
       :child_key => [:addressable_id], 
       Address.addressable_class => 'ParentModel'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object

Add :addressable_class and :addressable_id properties



21
22
23
24
# File 'lib/dm-address/polymorphic.rb', line 21

def included(klass)
  klass.__send__(:property, :addressable_class, String)
  klass.__send__(:property, :addressable_id, Integer)
end

Instance Method Details

#addressableObject

Return the addressable (that is, parent) record.



29
30
31
32
33
34
35
36
37
# File 'lib/dm-address/polymorphic.rb', line 29

def addressable
  parent_class_name = attribute_get(:addressable_class)
  # Remove a trailing method reference
  parent_split = parent_class_name.to_s.split('#')
  parent_class_name = parent_split[0..-2].join('#') if parent_split.length > 1
  return nil if parent_class_name.blank?
  parent_class = Object.full_const_get(parent_class_name)
  parent_class.get(attribute_get(:addressable_id))
end