26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
# File 'lib/trax/model/enum.rb', line 26
def as_enum(enum_name, args, options = {})
options.assert_valid_keys(:prefix, :source, :message)
options[:message] ||= "Is not a valid value for #{enum_name}"
options[:prefix] ||= true
options[:source] ||= enum_name
enum_values = args.is_a?(Hash) ? args.keys : args
validation_options = { :in => enum_values, :message => options.(:message) }
self.validates_inclusion_of(enum_name, validation_options)
scope_method_name = :"by_#{enum_name}"
scope_not_method_name = :"by_#{enum_name}_not"
self.scope scope_method_name, lambda { |*values|
enum_hash = self.__send__("#{enum_name}".pluralize).hash
where(enum_name => enum_hash.with_indifferent_access.slice(*values.flatten.compact.uniq).values)
}
self.scope scope_not_method_name, lambda { |*values|
enum_hash = self.__send__("#{enum_name}".pluralize).hash
where.not(enum_name => enum_hash.with_indifferent_access.slice(*values.flatten.compact.uniq).values)
}
super(enum_name, args, options)
end
|