3

您好我正在使用rails应用程序。我想实现用户标记为脸谱或叽叽喳喳做。当用户在Feed中发布时,他可以在开始时用@字符标记任何用户。如何在Facebook或Twitter等Feed中标记用户?

我使用Jquery UI Autocomplete plugin

我有这样的参考 Implementing jquery UI autocomplete to show suggestions when you type "@"这让我实现自动完成的部分。

但现在我想链接,自动完成用户名用户的个人资料网址例如:用户名=麦然后链接应该像

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

所以,请指导我,我怎么能在我的Rails应用程序中实现这一点?是有任何宝石可以这样做。

回答

1

嘿它不上面的方法要求。我用简单的正则表达式做了它。

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

<%[email protected]_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>}) %> 

在我正则表达式我已经使用(\^|\s|\B),因为@可以在字符串的开始或之后的空白,同时标注用户发生。

([a-zA-Z])(_?[a-zA-Z0-9]+)*|_([a-zA-Z0-9]+_?)*这是用来验证用户名。在我的应用程序中,用户名必须以字母开头,后跟字母&数字。

The no。 用于在正则表达式中进行第二次匹配。

详情尝试Rubular.com

正则表达式我希望这会帮助别人。

1

如果你想这样做,你应该写的文章内容具体的setter/getter方法。一个简单的例子:

在模型(在本例中与后列被称为“内容”):

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 

那么你应该使用在部分这些二传手/ getter方法。我只是写了这个“我的头”,可能会有一些语法的废话,但我认为你uznderstoud我在说什么!

这种方法的好处是,你还可以更改用户名东阳你存储用户的ID在岗位创造的时刻。

相关问题