retrospring/app/models/notification.rb

66 lines
1.7 KiB
Ruby
Raw Normal View History

2022-07-21 16:56:05 +02:00
# frozen_string_literal: true
2020-04-19 00:59:18 +02:00
class Notification < ApplicationRecord
2022-07-21 16:56:05 +02:00
belongs_to :recipient, class_name: "User"
2014-12-14 14:49:14 +01:00
belongs_to :target, polymorphic: true
2014-12-14 14:34:51 +01:00
class << self
include CursorPaginatable
define_cursor_paginator :cursored_for, :for
define_cursor_paginator :cursored_for_type, :for_type
def for(recipient, **kwargs)
where(kwargs.merge!(recipient: recipient)).order(:created_at).reverse_order
2014-12-14 14:34:51 +01:00
end
def for_type(recipient, type, **kwargs)
where(kwargs.merge!(recipient: recipient)).where(type: type).order(:created_at).reverse_order
end
2014-12-14 14:34:51 +01:00
def notify(recipient, target)
return nil unless target.respond_to? :notification_type
notif_type = target.notification_type
return nil unless notif_type
make_notification(recipient, target, notif_type)
end
2014-12-14 15:42:37 +01:00
def denotify(recipient, target)
return nil if recipient.blank?
2014-12-14 15:42:37 +01:00
return nil unless target.respond_to? :notification_type
notif_type = target.notification_type
return nil unless notif_type
2022-07-08 22:36:47 +02:00
notif = Notification.find_by(recipient: recipient, target: target)
2022-07-21 16:56:05 +02:00
notif&.destroy
2014-12-14 15:42:37 +01:00
end
2014-12-14 14:34:51 +01:00
private
2022-07-21 16:30:04 +02:00
def make_notification(recipient, target, notification_type)
return if get_notification_owner(target).present? && recipient.muting?(get_notification_owner(target))
2022-07-21 16:56:05 +02:00
n = notification_type.new(target: target,
2022-07-21 16:30:04 +02:00
recipient: recipient,
2022-07-21 16:56:05 +02:00
new: true)
2022-07-21 16:30:04 +02:00
n.save!
n
end
def get_notification_owner(target)
if target.is_a? User
target
elsif target&.user.is_a? User
target.user
elsif target&.source.is_a? User
target.source
else
nil
end
end
2014-12-14 14:34:51 +01:00
end
2014-12-13 19:30:10 +01:00
end