Class: EnumIsh::ActiveRecordDefiner
- Inherits:
-
Definer
- Object
- Definer
- EnumIsh::ActiveRecordDefiner
show all
- Defined in:
- lib/enum_ish/active_record_definer.rb
Instance Method Summary
collapse
Methods inherited from Definer
#define, #initialize
Instance Method Details
#define_accessor(enum) ⇒ Object
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
|
# File 'lib/enum_ish/active_record_definer.rb', line 22
def define_accessor(enum)
@klass.class_eval do
define_method enum.raw_method do
value = read_attribute(enum.name)
enum.mapping.fetch(value, value)
end
if ActiveRecord.version >= Gem::Version.new('7.2.0.a')
decorate_attributes([enum.name]) do |_, subtype|
EnumIsh::ActiveRecordEnumType.new(enum.name, enum.mapping, subtype)
end
elsif ActiveRecord.version > Gem::Version.new('7.0.0.a')
attribute(enum.name) do |subtype|
EnumIsh::ActiveRecordEnumType.new(enum.name, enum.mapping, subtype)
end
elsif ActiveRecord.version > Gem::Version.new('6.1.0.a')
decorate_attribute_type(enum.name) do |subtype|
EnumIsh::ActiveRecordEnumType.new(enum.name, enum.mapping, subtype)
end
else
decorate_attribute_type(enum.name, :enum) do |subtype|
EnumIsh::ActiveRecordEnumType.new(enum.name, enum.mapping, subtype)
end
end
end
end
|
#define_default(enum) ⇒ Object
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# File 'lib/enum_ish/active_record_definer.rb', line 7
def define_default(enum)
method = "_enum_ish_init_#{enum.name}".to_sym
@klass.class_eval do
after_initialize method
define_method method do
if respond_to?(enum.name) && public_send(enum.name).nil?
default = enum.default
default = instance_exec(&default) if default.kind_of?(Proc)
public_send("#{enum.name}=", default)
end
end
end
end
|
#define_scope(enum) ⇒ Object
49
50
51
52
53
54
55
56
57
58
|
# File 'lib/enum_ish/active_record_definer.rb', line 49
def define_scope(enum)
@klass.class_eval do
scope enum.scope_method, ->(*value) {
where(enum.name => enum.mapping.fetch(value, value))
}
scope enum.scope_method(:negative), ->(*value) {
where.not(enum.name => enum.mapping.fetch(value, value))
}
end
end
|