Module: HasMagicFields::Extend::ClassMethods

Defined in:
lib/has_magic_fields/extend.rb

Instance Method Summary collapse

Instance Method Details

#has_magic_fields(options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/has_magic_fields/extend.rb', line 8

def has_magic_fields(options = {})
  # Associations
  has_many :magic_attribute_relationships, :as => :owner, :dependent => :destroy
  has_many :magic_attributes, :through => :magic_attribute_relationships, :dependent => :destroy
  
  # Inheritence
  cattr_accessor :inherited_from


  # if options[:through] is supplied, treat as an inherited relationship
  if self.inherited_from = options[:through]
    class_eval do
      def inherited_magic_fields
        raise "Cannot inherit MagicFields from a non-existant association: #{@inherited_from}" unless self.class.method_defined?(inherited_from)# and self.send(inherited_from)
        self.send(inherited_from).magic_fields
      end
    end
    alias_method :magic_fields, :inherited_magic_fields unless method_defined? :magic_fields

  # otherwise the calling model has the relationships
  else
    has_many :magic_field_relationships, :as => :owner, :dependent => :destroy
    has_many :magic_fields, :through => :magic_field_relationships, :dependent => :destroy
    # alias_method_chain :magic_fields, :scoped
  end
  alias_method  :magic_fields_without_scoped, :magic_fields
end