我制作了一个助手方法来处理推文的正文,这样如果有任何提及,就会向其中添加一个链接。它确实做到了,但当提及的用户名与较长用户名的一部分匹配时(例如@test@test2(,只有@test会被链接。
生成的html如下所示:@test2 测试
我怎样才能使它看起来像这样:@test2 测试
这是我的助手方法:
def render_body(twit)
return twit.body unless twit.mentions.any?
processed_body = twit.body.to_s
twit.mentions.each do |mention|
processed_body = processed_body.gsub("@#{mention.user.username}", "<a href='/user/#{mention.user.id}'>@#{mention.user.username}</a>")
end
return processed_body.html_safe
end
我已经检查了数据库,它确实记录了@test2的提及,只是无法呈现它。
简单的字符串替换在这里不起作用,您必须使用锚定的正则表达式。这意味着你永远不会匹配一个单词的部分,只匹配整个单词:
processed_body = processed_body.gsub(/b@#{mention.user.username}b/,
"<a href='/user/#{mention.user.id}'>@#{mention.user.username}</a>")
在这里,我们用正则表达式替换了模式字符串,并使用b
将其锚定到单词边界。