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
|
# File 'app/models/concerns/acts_as_only_flagged.rb', line 37
def acts_as_only_flagged_enum(enum_name, flag_attr)
set_first_of_same_enum_method = "set_#{flag_attr}_on_first_of_#{enum_name}".to_sym
update_others_of_same_enum_method = "update_#{flag_attr}_on_others_of_#{enum_name}".to_sym
find_others_of_same_enum_method = "find_others_of_#{enum_name}".to_sym
before_save set_first_of_same_enum_method
define_method set_first_of_same_enum_method do
others = send(find_others_of_same_enum_method)
send("#{flag_attr}=", true) if others.empty?
end
after_save update_others_of_same_enum_method
define_method update_others_of_same_enum_method do
if send(flag_attr)
others = send(find_others_of_same_enum_method)
others.update_all(flag_attr => false) unless others.empty?
end
end
define_method find_others_of_same_enum_method do
enum_value = send(enum_name)
self.class.send(enum_value).where.not(id: id)
end
end
|