简体   繁体   中英

gsub method in Ruby

I'm a RoR newbie, and I'm attempting to figure out how to get the gsub method to add html to my page. Specifically, I'm attempting an exercise that, like Twitter, will route to an action that will list a Users tweets by linking their username. So, the string @username within the content property will link to /tweets/username listing out of the user's tweets. I have the action and route completed, but I can't get the gsub to work correctly. Here's what I thought would work

<%= content_tag :p, twet.content.gsub(/@[a-zA-z0-9]/, <html code here>)%>

but it doesn't. The html renders as text. To try to get around this, I also tried to create a link_to helper method using the $1 variable

<%= content_tag :p, twet.content.gsub(/@[a-zA-z0-9]/, link_to(("#{$1}", user_tweet_path($1)))%>

but that isn't working either. I've read other posts and learned that rails may not print html due to malicious code protection and $1 gets set after the sub, so I'm lost on how to make this work.

The variable twet needs to be set as html safe before it gets passed to content_tag . Try this:

<%= content_tag :p, twet.content.gsub(/@[a-zA-z0-9]/, <html code here>).html_safe %>

content_tag marks its output as HTML safe, but only after it has sanitized everything that was passed to it.

This isn't an answer to your question, but, besides the fact that you shouldn't do that in your view, your regexp pattern is flawed:

/@[a-zA-z0-9]/

Consider what it's doing:

[*'A'..'z', *'0'..'9'].join[/[a-zA-z0-9]+/]
 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz0123456789"

Az opens up the pattern to grab all characters from "A" to "z", including

[\]^_`

You probably don't want that.

Here's an example demonstrating it visually on Rubular.com.

尝试在第一种方法.html_safe添加到HTML字符串中。

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