Retrospring/app/models/subscription.rb

47 lines
1.2 KiB
Ruby
Raw Normal View History

2020-04-18 15:59:18 -07:00
class Subscription < ApplicationRecord
2015-04-20 18:12:11 -07:00
belongs_to :user
belongs_to :answer
class << self
2023-03-04 11:42:51 -08:00
def subscribe(recipient, target)
existing = Subscription.find_by(user: recipient, answer: target)
2023-03-04 11:42:51 -08:00
return true if existing.present?
Subscription.create!(user: recipient, answer: target)
2015-04-20 18:12:11 -07:00
end
def unsubscribe(recipient, target)
if recipient.nil? or target.nil?
return nil
end
subs = Subscription.find_by(user: recipient, answer: target)
2023-03-04 11:42:51 -08:00
subs&.destroy
2015-04-20 18:12:11 -07:00
end
def destruct(target)
if target.nil?
return nil
end
Subscription.where(answer: target).destroy_all
end
def notify(source, target)
return nil if source.nil? || target.nil?
2015-04-20 18:12:11 -07:00
notifications = Subscription.where(answer: target).where.not(user: target.user).map do |s|
{ target_id: source.id, target_type: Comment, recipient_id: s.user_id, new: true, type: Notification::Commented }
2015-04-20 18:12:11 -07:00
end
Notification.insert_all!(notifications)
2015-04-20 18:12:11 -07:00
end
def denotify(source, target)
return nil if source.nil? or target.nil?
subs = Subscription.where(answer: target)
Notification.where(target:, recipient: subs.map(&:user)).delete_all
2015-04-20 18:12:11 -07:00
end
end
end