Module: HasMagicColumns::ActiveRecord::ClassMethods

Defined in:
lib/has_magic_columns/active_record.rb

Instance Method Summary collapse

Instance Method Details

#has_magic_columns(options = {}) ⇒ Object



7
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/has_magic_columns/active_record.rb', line 7

def has_magic_columns(options = {})
  unless magical?
    # Associations
    has_many :magic_attribute_relationships, :as => :owner, :dependent => :destroy
    has_many :magic_attributes, :through => :magic_attribute_relationships, :dependent => :destroy
    
    # Eager loading - EXPERIMENTAL!
    if options[:eager]
      class_eval do
        def after_initialize
          initialize_magic_columns
        end
      end
    end
    
    # 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_columns
          raise "Cannot inherit MagicColumns from a non-existant association: #{@inherited_from}" unless self.class.method_defined?(inherited_from)# and self.send(inherited_from)
          self.send(inherited_from).magic_columns
        end
      end
      alias_method :magic_columns, :inherited_magic_columns unless method_defined? :magic_columns

    # otherwise the calling model has the relationships
    else
      has_many :magic_column_relationships, :as => :owner, :dependent => :destroy
      has_many :magic_columns, :through => :magic_column_relationships, :dependent => :destroy
    end
    
    # Hook into Base
    class_eval do
      alias_method :reload_without_magic, :reload
      alias_method :create_or_update_without_magic, :create_or_update
      alias_method :read_attribute_without_magic, :read_attribute
    end
  end
  include InstanceMethods
  
  # Add Magic to Base
  alias_method :reload, :reload_with_magic
  alias_method :read_attribute, :read_attribute_with_magic
  alias_method :create_or_update, :create_or_update_with_magic
end

#magical?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/has_magic_columns/active_record.rb', line 56

def magical?
  self.included_modules.include?(InstanceMethods)
end