2016-02-12 09:58:39 -05:00
|
|
|
# == 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
|
|
|
|
|
2016-10-31 15:19:14 -04:00
|
|
|
def subscribed?(user, to_project = nil)
|
|
|
|
if subscription = subscriptions.find_by(user: user, project: (to_project || project))
|
2016-03-01 11:33:13 -05:00
|
|
|
subscription.subscribed
|
|
|
|
else
|
2016-10-31 15:19:14 -04:00
|
|
|
subscribed_without_subscriptions?(user, to_project)
|
2016-02-12 09:58:39 -05:00
|
|
|
end
|
2016-03-01 11:33:13 -05:00
|
|
|
end
|
2016-02-12 09:58:39 -05:00
|
|
|
|
2016-03-01 11:33:13 -05:00
|
|
|
# Override this method to define custom logic to consider a subscribable as
|
|
|
|
# subscribed without an explicit subscription record.
|
2016-10-31 15:19:14 -04:00
|
|
|
def subscribed_without_subscriptions?(user, to_project = nil)
|
2016-03-01 11:33:13 -05:00
|
|
|
false
|
|
|
|
end
|
|
|
|
|
2016-10-31 15:19:14 -04:00
|
|
|
def subscribers(to_project = nil)
|
|
|
|
subscriptions.where(project: (to_project || project), subscribed: true).map(&:user)
|
2016-02-12 09:58:39 -05:00
|
|
|
end
|
|
|
|
|
2016-10-31 15:19:14 -04:00
|
|
|
def toggle_subscription(user, to_project = nil)
|
|
|
|
subscribed = subscribed?(user, (to_project || project))
|
|
|
|
|
|
|
|
find_or_initialize_subscription(user, to_project).
|
|
|
|
update(subscribed: !subscribed)
|
2016-02-12 09:58:39 -05:00
|
|
|
end
|
|
|
|
|
2016-10-31 15:19:14 -04:00
|
|
|
def subscribe(user, to_project = nil)
|
|
|
|
find_or_initialize_subscription(user, to_project).
|
2016-05-12 16:48:09 -04:00
|
|
|
update(subscribed: true)
|
|
|
|
end
|
|
|
|
|
2016-10-31 15:19:14 -04:00
|
|
|
def unsubscribe(user, to_project = nil)
|
|
|
|
find_or_initialize_subscription(user, to_project).
|
2016-02-12 09:58:39 -05:00
|
|
|
update(subscribed: false)
|
|
|
|
end
|
2016-10-31 15:19:14 -04:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def find_or_initialize_subscription(user, to_project = nil)
|
|
|
|
subscriptions.
|
|
|
|
find_or_initialize_by(user_id: user.id, project_id: (to_project || project).id)
|
|
|
|
end
|
2016-02-12 09:58:39 -05:00
|
|
|
end
|