I've made a helper method that processes a tweet's body so that if there is any mentions a link will be added to it. It does do it, but when a username mentioned matches a part of a longer username (e.g @test @test2) only @test will be linked.
The resulting html looks like this: @test @test2
How can I make it look like this: @test @test2
This is my helper method:
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
I've checked the db and it does record the mention of @test2, it's just not able to render it.
A simple string substitution won't work here, you will have to use an anchored regex. This means that you never match parts of a word, only whole words:
processed_body = processed_body.gsub(/\b@#{mention.user.username}\b/,
"<a href='/user/#{mention.user.id}'>@#{mention.user.username}</a>")
Here we replaced the pattern string with a regex and used \b
to anchor it to word boundaries.