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
|
# File 'lib/acts_as_constant.rb', line 10
def acts_as_constant(col = :name)
begin
klass = self.to_s
const = klass.upcase.gsub("::", "_")
class_eval %{
private
#{const}_CONSTANTS = []
public
def self.get(id)
return nil if id.blank?
#{const}_CONSTANTS[id]
end
def self.CONSTANTS
#{const}_CONSTANTS
end
}
rows = eval "#{klass}.find(:all)"
rows.each do |rec|
name = rec.send(col)
unless name.nil?
name = name.downcase
name = name.gsub(' ', '_')
class_eval %{
# by using .freeze we can prevent the object from being modified.
#{const}_CONSTANTS[#{rec.id}] = rec.freeze
def self.#{name}
#{const}_CONSTANTS[#{rec.id}]
end
def self.#{name.upcase}
#{const}_CONSTANTS[#{rec.id}]
end
}
end
end
class_eval %{
# by using .freeze we can prevent the constants array from being modified.
#{const}_CONSTANTS.freeze
}
rescue => ex
end
end
|