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
|
# File 'lib/rails_column_enumerator.rb', line 19
def enumerated_column(column_name, enumerated_values, options = {})
enum_name = column_name.to_s.pluralize.upcase.to_sym
enum_symbols_name = (column_name.to_s.upcase + '_NAMES').to_sym
self.const_set(enum_name, enumerated_values.with_indifferent_access)
self.const_set(enum_symbols_name, enumerated_values.invert)
= options.delete(:selections)
if
.each do |name, options|
self.class.send(:define_method, name.to_s) { options.map{ |key| RailsColumnEnumerator.get_record(key, self.const_get(enum_name), self.const_get(enum_symbols_name), name, column_name, self.name.underscore.downcase) } }
end
end
self.send(:define_method, column_name) do |return_symbol = false|
return_symbol ? self.class.const_get(enum_symbols_name)[read_attribute(column_name)].to_sym : read_attribute(column_name)
end
self.send(:define_method, column_name.to_s + '=') do |val|
write_attribute(column_name, RailsColumnEnumerator.get_int(val, self.class.const_get(enum_name)))
end
enumerated_values.keys.each do |key|
self.send(:define_method, key.to_s + '?') do
key.to_sym == self.send(column_name, true)
end
end
enumerator_associations = options.delete(:scopes)
if enumerator_associations
enumerator_associations.each do |key,values|
found_values = values.map { |val| RailsColumnEnumerator.get_int(val, self.const_get(enum_name), self.const_get(enum_symbols_name)) }
raise "You must provide some values for the scope." if found_values.blank?
self.define_singleton_method(key) do
self.where(column_name => found_values)
end
self.send(:define_method, key.to_s + "_include?") do |val|
found_values.include?(RailsColumnEnumerator.get_int(val, self.class.const_get(enum_name)))
end
end
end
options.merge!(inclusion: const_get(enum_name).values) unless options[:inclusion].present?
validates column_name, options
end
|