BigW Consortium Gitlab

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

module Subscribable
  extend ActiveSupport::Concern

  included do
    has_many :subscriptions, dependent: :destroy, as: :subscribable
  end

15
  def subscribed?(user, project = nil)
16
    if subscription = subscriptions.find_by(user: user, project: project)
17 18
      subscription.subscribed
    else
19
      subscribed_without_subscriptions?(user, project)
20
    end
21
  end
22

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

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

35
  def toggle_subscription(user, project = nil)
36 37
    unsubscribe_from_other_levels(user, project)

38 39
    find_or_initialize_subscription(user, project).
      update(subscribed: !subscribed?(user, project))
40 41
  end

42
  def subscribe(user, project = nil)
43 44 45 46
    unsubscribe_from_other_levels(user, project)

    find_or_initialize_subscription(user, project)
      .update(subscribed: true)
47 48
  end

49
  def unsubscribe(user, project = nil)
50 51 52 53
    unsubscribe_from_other_levels(user, project)

    find_or_initialize_subscription(user, project)
      .update(subscribed: false)
54
  end
55 56 57

  private

58 59 60 61 62 63 64 65 66 67 68 69 70
  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

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

  def subscriptions_available(project)
    t = Subscription.arel_table

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