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
106
107
108
109
110
111
112
|
# File 'lib/enum_attribute.rb', line 10
def enum_attribute name, values, opts={:number=>false,:colum_name=>false,:i18n=>true}
raise "Values should be given as Enumerable" unless values.is_a?(Enumerable)
values = values.map(&:to_s)
pluralized = name.to_s.pluralize
extend Module.new{
define_method pluralized do
values
end
define_method "#{name}_names" do
if opts[:i18n] == false
values
else
values.map{|n|self.i18nt(n,pluralized)}
end
end
define_method "#{name}_pairs" do
if opts[:number]
values.each_with_index.map{|n,i|[ self.i18nt(n,pluralized), i + 1]}
else
values.map{|n|[ self.i18nt(n,pluralized), n]}
end
end
define_method "#{name}_name" do |col|
return "" if col.blank?
if col.to_i==0 return "" unless values.any?{|v| v == col.to_s}
self.i18nt(col,pluralized)
else
return "" if values.size < col.to_i
self.i18nt(values[col - 1],pluralized)
end
end
def i18nt(value,pluralized)
return "" unless value
i18n_scope = "activerecord"
i18n_scope = self.i18n_scope.to_s if defined?(self.i18n_scope) I18n.t("#{i18n_scope}.attributes.#{self.model_name.to_s.underscore}.#{pluralized}.#{value}")
end
}
define_method "#{name}_seed" do
column_name = name
column_name = opts[:column_name] if opts[:column_name]
if opts[:number]
return "" if __send__(column_name).to_i - 1 < 0
values[__send__(column_name).to_i - 1]
else
column_name
end
end
define_method "#{name}_name" do |*locale|
column_name = name
column_name = opts[:column_name] if opts[:column_name]
return "" unless __send__(column_name)
if opts[:number]
return "" if __send__(column_name).to_i - 1 < 0
value = values[__send__(column_name).to_i - 1]
else
value = __send__(column_name)
end
return value if opts[:i18n] == false
l = :en
l = I18n.locale if defined?(I18n.locale)
l = locale[0] if locale
i18n_scope = "activerecord"
i18n_scope = self.i18n_scope.to_s if defined?(self.i18n_scope) I18n.t("#{i18n_scope}.attributes.#{self.model_name.to_s.underscore}.#{pluralized}.#{value}",:locale=>l)
end
end
|