BigW Consortium Gitlab

subscribable.rb 2.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
# == Subscribable concern
#
# Users can subscribe to these models.
#
# Used by Issue, MergeRequest, Label
#

module Subscribable
  extend ActiveSupport::Concern

  included do
12
    has_many :subscriptions, dependent: :destroy, as: :subscribable # rubocop:disable Cop/ActiveRecordDependent
13 14
  end

15
  def subscribed?(user, project = nil)
16 17
    return false unless user

18
    if subscription = subscriptions.find_by(user: user, project: project)
19 20
      subscription.subscribed
    else
21
      subscribed_without_subscriptions?(user, project)
22
    end
23
  end
24

25 26
  # Override this method to define custom logic to consider a subscribable as
  # subscribed without an explicit subscription record.
27
  def subscribed_without_subscriptions?(user, project)
28 29 30
    false
  end

31
  def subscribers(project)
32 33 34
    subscriptions_available(project)
      .where(subscribed: true)
      .map(&:user)
35 36
  end

37
  def toggle_subscription(user, project = nil)
38 39
    unsubscribe_from_other_levels(user, project)

40 41
    find_or_initialize_subscription(user, project)
      .update(subscribed: !subscribed?(user, project))
42 43
  end

44
  def subscribe(user, project = nil)
45 46 47 48
    unsubscribe_from_other_levels(user, project)

    find_or_initialize_subscription(user, project)
      .update(subscribed: true)
49 50
  end

51
  def unsubscribe(user, project = nil)
52 53 54 55
    unsubscribe_from_other_levels(user, project)

    find_or_initialize_subscription(user, project)
      .update(subscribed: false)
56
  end
57 58 59

  private

60 61 62 63 64 65 66 67 68 69 70 71 72
  def unsubscribe_from_other_levels(user, project)
    other_subscriptions = subscriptions.where(user: user)

    other_subscriptions =
      if project.blank?
        other_subscriptions.where.not(project: nil)
      else
        other_subscriptions.where(project: nil)
      end

    other_subscriptions.update_all(subscribed: false)
  end

73
  def find_or_initialize_subscription(user, project)
74 75
    subscriptions
      .find_or_initialize_by(user_id: user.id, project_id: project.try(:id))
76 77 78 79 80
  end

  def subscriptions_available(project)
    t = Subscription.arel_table

81 82
    subscriptions
      .where(t[:project_id].eq(nil).or(t[:project_id].eq(project.try(:id))))
83
  end
84
end