Module: ActiveRecord::Acts::MagicModel::ClassMethods

Defined in:
lib/acts_as_magic_model.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#acts_as_magic_modelObject



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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/acts_as_magic_model.rb', line 20

def acts_as_magic_model
  # Make sure we are working with a current representation of
  # the table
  self.reset_column_information

  class_eval do
    sys_tables = self.connection.tables
    my_table = self.table_name
    my_columns = self.column_names

    # Try first to guess any belongs_to relations based on its
    # attributes
    my_columns.each do |attr|
      next unless attr =~ /_id$/
      base_attr = attr.gsub(/_id$/, '').pluralize
      if self.connection.tables.include? base_attr
        self.belongs_to base_attr.singularize
        klass = find_or_declare_class_for(base_attr)
        klass.class_eval "has_many :#{self.to_s.tableize}"

        # Is the acts_as_catalog plugin present? If so, and
        # the other table is a catalog, add the convenience
        # othertable_name methods
        if klass.respond_to?('is_catalog?') and klass.is_catalog?
          eval %Q(def #{base_attr.singularize}_name
                    return nil if #{base_attr.singularize}.nil?
                    #{base_attr.singularize}.name
                  end)
        end
      end
    end

    # Now, go over the has_many and HABTM relations with other tables
    sys_tables.each do |tbl|
      cols = self.connection.columns(tbl).map {|c| c.name}
      next unless cols.include? "#{my_table.singularize}_id"

      # Is this a HABTM table? (Be strict here: Only tables with 
      # exactly two columns)
      if cols.size == 2 and
          (tbl=~ /^#{my_table}_(.+)/ or tbl=~ /^(.+)_#{my_table}$/)
        other_tbl = $1
        self.has_and_belongs_to_many other_tbl

        begin
          klass = other_tbl.classify.constantize
        rescue NameError
          eval "class ::#{other_tbl.classify} < ActiveRecord::Base; end"
          klass = other_tbl.classify.constantize
        end
        klass.class_eval "has_and_belongs_to_many :#{self.to_s.tableize}"
        next
      end

      self.has_many tbl
    end

  end
end

#auto_magic_modelsObject



9
10
11
12
13
14
15
16
17
18
# File 'lib/acts_as_magic_model.rb', line 9

def auto_magic_models
  self.connection.tables.each do |table|
    next if table == 'schema_info'
    ###
    ### We should also skip the relation tables
    ###
    klass = find_or_declare_class_for(table)
    klass.acts_as_magic_model
  end
end