mention_helper.rb 1.42 KB
module MentionHelper
  def mention_search_regex
    /(?:^\s?|\s)@([^\s?:^\.?:^\,]+)/m
  end

  def has_mentions? text=""
    text.scan(mention_search_regex).present?
  end

  def get_mentions text=""
    text.scan(mention_search_regex).flatten.uniq
  end

  def get_invalid_mentions text, person, profile=nil
    mentions = get_mentions text
    # remove the friends of the user
    mentions -= person.friends.select(:identifier).where(:identifier => mentions).map(&:identifier)

    if profile.present? and profile.kind_of?(Community)
      # remove the members of the same community
      mentions -= profile.members.where(:identifier => mentions).map(&:identifier)
    end

    # any remaining mention is invalid
    mentions
  end

  def remove_invalid_mentions text, invalid_mentions=[]
    if not invalid_mentions.empty?
      # remove the "@" from the invalid mentions, so that the notify job dont send notifications to them
      invalid_mentions.each do |mention|
        text.gsub! "@#{mention}", mention
      end
    end

    text
  end

  def has_valid_mentions? model, attribute, person, profile=nil
    text = model.send attribute

    if has_mentions? text
      invalid_mentions = get_invalid_mentions text, person, profile
      text = remove_invalid_mentions text, invalid_mentions
      # to prevent invalid notifications, remove the invalid mentions
      model.update_attribute attribute, text
    end

    has_mentions? text
  end
end