Module: ActsAsReactable::Reactable::ClassMethod

Defined in:
lib/acts_as_reactable/reactor.rb,
lib/acts_as_reactable/reactable.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_reactableObject



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
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
65
66
67
68
69
# File 'lib/acts_as_reactable/reactable.rb', line 10

def acts_as_reactable
  has_many :reactions, class_name: "ActsAsReactable::Reaction", as: :reactable, dependent: :delete_all

  define_method :destroy_reaction_from do |reactor|
    raise "InvalidReactor" if !reactor

    puts reaction = reactions.find_by(reactor: reactor)
    return unless (reaction = reactions.find_by(reactor: reactor))
    reaction.destroy
  end

  define_method :update_reaction_from do |reactor, emoji = nil|
    raise "InvalidReactor" if !reactor

    if !emoji
      return destroy_reaction_from(reactor)
    end

    reaction = reactions.where({reactor: reactor, emoji: emoji}).first_or_create
    reaction
  end

  define_method :add_reactions do |reactor, emoji_or_list = nil|
    return unless emoji_or_list

    emojis = if emoji_or_list.is_a?(Array)
      emoji_or_list
    else
      [emoji_or_list]
    end

    # TODO performance
    # optimize by using a single query
    emojis
      .compact
      .uniq
      .each do |emoji|
        reaction = reactions.find_or_create_by(reactor: reactor, emoji: emoji)
        reaction.save unless reaction.persisted?
      end

    self
  end

  define_method :remove_reactions do |reactor, emoji_or_list = nil|
    return unless emoji_or_list

    emojis = if emoji_or_list.is_a?(Array)
      emoji_or_list
    else
      [emoji_or_list]
    end

    reactions
      .where(reactor: reactor, emoji: emojis.compact.uniq)
      .destroy_all

    self
  end
end

#acts_as_reactorObject



10
11
12
# File 'lib/acts_as_reactable/reactor.rb', line 10

def acts_as_reactor
  has_many :reactions, class_name: "ActsAsReactable::Reaction", as: :reactor, dependent: :delete_all
end