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
self.reset_column_information
class_eval do
sys_tables = self.connection.tables
my_table = self.table_name
my_columns = self.column_names
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}"
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
sys_tables.each do |tbl|
cols = self.connection.columns(tbl).map {|c| c.name}
next unless cols.include? "#{my_table.singularize}_id"
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
|