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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
# File 'lib/acts_as_constant.rb', line 10
def acts_as_constant(col = :name)
begin
klass = self.to_s
const = klass.upcase.gsub("::", "_")
define_method("constantize") do
self.send(col).constantize
end
class_eval %{
def self.constant_class_name
"#{const}"
end
def self.constant_column
"#{col}"
end
}
class_eval %{
private
#{self.constant_class_name}_CONSTANTS = []
public
def self.get(id)
return nil if id.blank?
#{self.constant_class_name}_CONSTANTS[id]
end
def self.CONSTANTS
#{self.constant_class_name}_CONSTANTS
end
}
class_eval do
def self.reload_constants!
begin
self.CONSTANTS.clear
rows = eval "#{self.to_s}.find(:all)"
rows.each do |rec|
name = rec.send(self.constant_column)
unless name.nil?
name = name.underscore.gsub("/", '_')
self.instance_eval do
define_method("constant_name") do
self.send(self.constant_column).downcase.gsub(' ', '_')
end
end
class_eval %{
# by using .freeze we can prevent the object from being modified.
#{self.constant_class_name}_CONSTANTS[#{rec.id}] = rec.freeze
def self.#{name}
#{self.constant_class_name}_CONSTANTS[#{rec.id}]
end
def self.#{name.upcase}
#{self.constant_class_name}_CONSTANTS[#{rec.id}]
end
}
end
end
rescue Exception => e
end
end
end
self.reload_constants!
rescue => ex
end
end
|