docbrown/app/services/mentions/create_all.rb
aRtoo 05cfe16e1c Fix comment author being notified when mentioning itself (#4456)
* added a condition to check if owner of the comment is in mentions

* added a test to check if comment owner can mention self

* fixed metion test by:
  - adding a second user to simulate a owner of a comment
  - change the user on comment to owned by newly created user
2019-10-25 10:23:45 -04:00

47 lines
1.4 KiB
Ruby

module Mentions
class CreateAll
def initialize(notifiable)
@notifiable = notifiable
end
def self.call(*args)
new(*args).call
end
def call
# Only works for comments right now.
# Paired with the process that creates the "comment-mentioned-user"
doc = Nokogiri::HTML(notifiable.processed_html)
usernames = []
mentions = []
doc.css(".comment-mentioned-user").each do |link|
username = link.text.delete("@").downcase
user = User.find_by(username: username)
if user && user.id != notifiable.user_id
usernames << username
mentions << create_mention(user)
end
end
delete_removed_mentions(usernames)
mentions
end
private
def delete_removed_mentions(usernames)
users = User.where(username: usernames)
mentions = @notifiable.mentions.where.not(user_id: users).destroy_all
Notification.remove_all(notifiable_ids: mentions.pluck(:id), notifiable_type: "Mention") if mentions.present?
end
def create_mention(user)
mention = Mention.create(user_id: user.id, mentionable_id: @notifiable.id, mentionable_type: @notifiable.class.name)
# mentionable_type = model that created the mention, user = user to be mentioned
Notification.send_mention_notification(mention)
mention
end
attr_reader :notifiable
end
end