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

谁说胖子不能爱 提交于 2019-12-21 19:59:53

问题


In my Rails 4 app, I have a Post model, with :copy and :short_copy as custom attributes (strings).

These attributes contain copies for social medias (Facebook, Twitter, Instagram, Pinterest, etc.).

I display the content of these attributes in my Posts#Show view.

Currently, URLs, #hashtags and @mentions are formatted like the rest of the text.

What I would like to do is to format them in a different fashion, for instance in another color or in bold.

I found the twitter-text gem, which seems to offer such features, but my problem is that I do NOT need — and do NOT want — to have these URLs, #hashtags and @mentions turn into real links.

Indeed, it looks like the twitter-text gem converts URLs, #hashtags and @mentions by default with Twitter::Autolink, as explained in this Stack Overflow question.

That's is not what I am looking for: I just want to update the style of my URLs, #hashtags and @mentions.

How can I do this in Ruby / Rails?

—————

UPDATE:

Following Wes Foster's answer, I implemented the following method in post.rb:

def highlight(string)
  string.gsub!(/\S*#(\[[^\]]+\]|\S+)/, '<span class="highlight">\1</span>')
end

Then, I defined the following CSS class:

.highlight {
    color: #337ab7;
}

Last, I implemented <%= highlight(post.copy) %> in the desired view.

I now get the following error:

ArgumentError
wrong number of arguments (1 for 2..3)
<td><%= highlight(post.copy) %></td>

What am I doing wrong?

—————


回答1:


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.



来源:https://stackoverflow.com/questions/33242512/rails-4-how-to-identify-and-format-links-hashtags-and-mentions-in-model-attrib

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