Implementing Notifications in Rails

后端 未结 6 1203
渐次进展
渐次进展 2021-01-30 03:51

In my application, I want to notify a user, when he/she is mentioned in a comment or a post.
The user handle is @user_name, similar to Facebook

6条回答
  •  粉色の甜心
    2021-01-30 04:02

    I know this question is outdated but I released a MentionSystem gem recently to rubygems.org that allows to create mentions between mentionee objects and mentioners, it also allows you to detect mentions in facebook / twitter styler like @username1 and #hashtag in order to create the mentions.

    The gem is hosted at github: https://github.com/pmviva/mention_system

    Lets say you have a Post that can mention users in the form of @username.

    you have the class

    class Post < ActiveRecord::Base
      act_as_mentioner
    end
    

    and

    class User < ActiveRecord::Base
      act_as_mentionee
    end
    

    Then you define a custom mention processor:

    class PostMentionProcessor < MentionSystem::MentionProcessor
      def extract_mentioner_content(post)
        return post.content
      end
    
      def find_mentionees_by_handles(*handles)
        User.where(username: handles)
      end
    end
    

    Then in your Posts controller create action you have:

    def create
      @post = Post.new(params[:post])
      if @post.save
        m = PostMentionProcessor.new
        m.add_after_callback Proc.new { |post, user| UserMailer.notify_mention(post, user) }
        m.process_mentions(post)
      end
    
      respond_with @post
    end
    

    If your post has @user1, @user2 and @user3 in its content the mention processor will parse user1, user2, user3, will find users with username [user1, user2, user3] and then create the mentions in the database, after each of the mentions it will run the after callback that in the example will send an email notifying the mention between post and user.

提交回复
热议问题