BigW Consortium Gitlab

subscribable.rb 1.09 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# == 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

  def subscribed?(user)
16 17 18 19
    if subscription = subscriptions.find_by_user_id(user.id)
      subscription.subscribed
    else
      subscribed_without_subscriptions?(user)
20
    end
21
  end
22

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

  def subscribers
    subscriptions.where(subscribed: true).map(&:user)
31 32 33 34 35 36 37 38
  end

  def toggle_subscription(user)
    subscriptions.
      find_or_initialize_by(user_id: user.id).
      update(subscribed: !subscribed?(user))
  end

39 40 41 42 43 44
  def subscribe(user)
    subscriptions.
      find_or_initialize_by(user_id: user.id).
      update(subscribed: true)
  end

45 46 47 48 49 50
  def unsubscribe(user)
    subscriptions.
      find_or_initialize_by(user_id: user.id).
      update(subscribed: false)
  end
end