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