嗨,我正在开发一个rails应用程序。我想实现像facebook或twitter那样的用户标签。当用户在提要中发帖时,他可以在开始时用@字符标记任何用户。
我正在使用Jquery UI Autocomplete plugin。
我有这个参考Implementing jquery UI autocomplete to show suggestions when you type "@",它帮助我实现了自动补全部分。
但现在我想将自动完成的用户名链接到用户配置文件url,例如username = Mak,然后链接应生成如下所示
<a href="http://www.example.com/username">Username</a>
所以请指导我如何在我的rails应用程序中实现这一点?有没有什么好办法可以做到的?
发布于 2011-10-31 10:02:19
嘿,它不需要上面的方法。我是用简单的正则表达式完成的。
<% @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>}) %>
在我的正则表达式中,我使用了(\^|\s|\B)
,因为在标记用户时,@可以出现在字符串的开头或空格之后。
([a-zA-Z])(_?[a-zA-Z0-9]+)*|_([a-zA-Z0-9]+_?)*
验证用户名。在我的应用程序中,用户名必须以字母开头,然后是字母和数字。
没有。2用于在正则表达式中进行第二次匹配。
有关更多详细信息,请尝试Rubular.com上的正则表达式
我希望这会对其他人有所帮助。
发布于 2011-10-21 12:28:24
如果你想这样做,你应该为post内容编写特定的setter/getter方法。一个简单的例子:
在模型中(在本例中,包含帖子的列称为"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
然后,您应该在部分代码中使用这些setter/getter方法。我只是写了这个“从我的头脑”可能有一些句法废话,但我认为你更明白我在说什么!
THe这种方法的优点是,您还可以更改用户名,因为您在创建帖子时存储了用户的id。
https://stackoverflow.com/questions/7848337
复制