我正在制作一个提及功能,所以当用户输入@时,他们为用户名输入的下一部分是可点击的,直到出现空格。这是假设他们正确输入用户名,只有字母和数字。如果他们输入“Hi @jon!”,我需要它才能工作。它会发现感叹号(或任何不是字母或数字的符号)不是用户名的一部分而是排除它而不只是寻找下面的空格。
这就是我所拥有的:
while @comment.content.include? "@" do
at = @comment.content.index('@')
space = @comment.content.index(' ', at)
length = space - at
usernotag = @comment.content[at + 1,length - 1]
userwtag = @comment.content[at,length]
@user = User.where(:username => usernotag.downcase).first
@mentioned_users.push(@user)
replacewith = "<a href='/" + usernotag + "'>*%^$&*)()_+!$" + usernotag + "</a>"
@comment.content = @comment.content.gsub(userwtag, replacewith)
end
@comment.content = @comment.content.gsub("*%^$&*)()_+!$", "@")
知道我应该做什么吗?
答案 0 :(得分:1)
您应该使用正则表达式来解析/提取用户引用:
# Transform comment content inline.
@comment.content.gsub!(/@[\w\d]+/) {|user_ref| link_if_user_reference(user_ref) }
@comment.save!
# Helper to generate a link to the user, if user exists
def link_if_user_reference(user_ref)
username = user_ref[1..-1]
return user_ref unless User.find_by_name(username)
link_to user_ref, "/users/#{user_name}"
# => produces link @username => /user/username
end
这假设您的用户名仅限于您所说的字母数字字符(字母或数字)。如果您有其他字符,则可以将它们添加到正则表达式中包含的集合中。