Module: ActsAsOnlyFlagged::ClassMethods

Defined in:
app/models/concerns/acts_as_only_flagged.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_only_flagged(parent_association, child_association, flag_attr) ⇒ Object



5
6
7
8
9
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
# File 'app/models/concerns/acts_as_only_flagged.rb', line 5

def acts_as_only_flagged(parent_association, child_association, flag_attr)
  children_name = child_association.to_s
  child_name = children_name.singularize

  set_first_child_method = "set_#{flag_attr}_on_first_#{child_name}".to_sym
  update_siblings_method = "update_#{flag_attr}_on_sibling_#{children_name}".to_sym
  find_siblings_method = "find_#{parent_association}_other_#{children_name}".to_sym

  before_save set_first_child_method

  define_method set_first_child_method do
    siblings = send(find_siblings_method)
    send("#{flag_attr}=", true) if siblings.empty?
  end

  after_save update_siblings_method

  define_method update_siblings_method do
    if send(flag_attr)
      siblings = send(find_siblings_method)
      siblings.update_all(flag_attr => false) unless siblings.empty?
    end
  end

  define_method find_siblings_method do
    # handle nil parent
    return [] unless parent = send(parent_association)

    parent.send(child_association).where.not(id: id)
  end
end

#acts_as_only_flagged_enum(enum_name, flag_attr) ⇒ Object



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