How to tag users in feed like Facebook or Twitter does?

霸气de小男生 提交于 2019-12-10 21:43:54

问题


HI I am working on a rails application. I want to implement user tagging as facebook or twitter does. When user is posting in feed he can tag any user with @ character at starting.

I am using Jquery UI Autocomplete plugin.

I have this reference Implementing jquery UI autocomplete to show suggestions when you type "@" which helped me to implement auto complete part.

But now I want to link that auto completed username to users profile url e.g Username = Mak then link should be generated like

<a href="http://www.example.com/username">Username</a>

So please guide me how can I implement this in my rails application?Is there any gem to do so.


回答1:


If you want to do that you should write specific setter/getter methods for the post content. A simple example:

In model (in this example the column with the post is called "content"):

attr_reader :set_content
attr_accessor :set_content
attr_reader :get_content
attr_accessor :get_content
def set_content=(content)   

     users = content.scan(/\@(.*)\ /)
     users.each do |user_name|
          user = User.find_by_name(user_name[1])
          content.gsub!("@#{user_name[1]}", "|UID:#{user.id}|") unless user.nil?
     end
     self.content=content
end

def get_content
     current_content=self.content
     users = self.content.scan(/\|UID\:([0-9]*)\|/)
     users.each do |user_id|
          user = User.find(user_id[1])
          current_content.gsub!("|UID:#{user_id[1]}|", "<your link stuff here>")
     end
     current_content
end

Then you should use these setter/getter methods in the partial. I just wrote this "out of my head" there might be some syntactical crap in it but I think you uznderstoud what Im talking about!

THe advantage of this method is that you can also change the users names beacause you store the id of the user at the moment of posts creation.




回答2:


Hey it doesn't required above methods. I did it using simple regex.

<% @str = @madyrocks solved problem of @username tagging %>

<%=@result_string = @str.gsub(/(\^|\s|\B)@(([a-zA-Z])(_?[a-zA-Z0-9]+)*|_([a-zA-Z0-9]+_?)*)/i, 
%Q{ <a href="http://example.com/\\2">\@\\2</a>}) %>

In my regex I have used (\^|\s|\B) because @ can occur at start of string or after a white space while tagging a user.

([a-zA-Z])(_?[a-zA-Z0-9]+)*|_([a-zA-Z0-9]+_?)* This is used to validate username. In my application username must start with alphabet followed by alphabets & numbers.

The no. 2 used to take second match in regex.

For more details try the regex on Rubular.com

I hope this will help others.



来源:https://stackoverflow.com/questions/7848337/how-to-tag-users-in-feed-like-facebook-or-twitter-does

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!