Rails 4: how to identify and format links, hashtags and mentions in model attributes?

依然范特西╮ 提交于 2019-12-04 14:59:18

I'm sure each of the following regex patterns could be improved to match even more options, however, the following code works for me:

def highlight_url(str)
    str.gsub!(/(https?:\/\/[\S]+)/, '[\1]')
end

def highlight_hashtag(str)
    str.gsub!(/\S*#(\[[^\]]+\]|\S+)/, '[#\1]')
end

def highlight_mention(str)
    str.gsub!(/\B(\@[a-z0-9_-]+)/i, '[\1]')
end

# Initial string
str = "Myself and @doggirl bought a new car: http://carpictures.com #nomoremoney"

# Pass through each
highlight_mention(str)
highlight_hashtag(str)
highlight_url(str)

puts str   # > Myself and [@doggirl] bought a new car: [http://carpictures.com] [#nomoremoney]

In this example, I've wrapped the matches with brackets []. You should use a span tag and style it. Also, you can wrap all three gsub! into a single method for simplicity.

Updated for the asker's add-on error question

It looks like the error is references another method named highlight. Try changing the name of the method from highlight to new_highlight to see if that fixes the new problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!