2020-04-19 00:59:18 +02:00
|
|
|
class Notification < ApplicationRecord
|
2014-12-14 14:34:51 +01: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
|
2020-04-20 23:03:57 +02:00
|
|
|
include CursorPaginatable
|
|
|
|
|
|
|
|
define_cursor_paginator :cursored_for, :for
|
|
|
|
define_cursor_paginator :cursored_for_type, :for_type
|
|
|
|
|
2014-12-14 14:34:51 +01:00
|
|
|
def for(recipient, options={})
|
2015-02-10 07:04:49 +01:00
|
|
|
self.where(options.merge!(recipient: recipient)).order(:created_at).reverse_order
|
2014-12-14 14:34:51 +01:00
|
|
|
end
|
|
|
|
|
2020-04-20 23:03:57 +02:00
|
|
|
def for_type(recipient, type, options={})
|
|
|
|
self.where(options.merge!(recipient: recipient)).where('LOWER(target_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 unless target.respond_to? :notification_type
|
|
|
|
|
|
|
|
notif_type = target.notification_type
|
|
|
|
return nil unless notif_type
|
|
|
|
|
2014-12-14 15:48:10 +01:00
|
|
|
notif = notif_type.find_by(recipient: recipient, target: target)
|
|
|
|
notif.destroy unless notif.nil?
|
2014-12-14 15:42:37 +01:00
|
|
|
end
|
|
|
|
|
2014-12-14 14:34:51 +01:00
|
|
|
private
|
|
|
|
|
|
|
|
def make_notification(recipient, target, notification_type)
|
|
|
|
n = notification_type.new(target: target,
|
2022-03-26 12:51:29 +01:00
|
|
|
target_type: target.class.name, # To ensure we don't get a type of 'Appenddable'
|
2014-12-14 14:34:51 +01:00
|
|
|
recipient: recipient,
|
|
|
|
new: true)
|
|
|
|
n.save!
|
|
|
|
n
|
|
|
|
end
|
|
|
|
end
|
2014-12-13 19:30:10 +01:00
|
|
|
end
|