简体   繁体   中英

How do I fix rendering mentions with link (e.g. "@test @test2") but @test2 links to @test's page

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 (eg @test @test2) only @test will be linked.

The resulting html looks like this: @test @test 2

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM