0

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.

mike0416
  • 461
  • 4
  • 17
  • 3
    Unrelated, but I'd hesitate to put this kind of logic in the view. Seems like it wants to be extracted to a helper, decorator, etc. – Dave Newton Dec 19 '14 at 19:54
  • See "[raw vs. html_safe vs. h to unescape html](http://stackoverflow.com/questions/4251284/raw-vs-html-safe-vs-h-to-unescape-html)" – the Tin Man Dec 19 '14 at 19:59

3 Answers3

0

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.

Corey Woodcox
  • 96
  • 1
  • 5
0

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"

A-z 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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
-1

Try adding .html_safe to the HTML String in the first method.

tagCincy
  • 1,589
  • 10
  • 20