Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to do find a pattern and replace with a link in a Rails view

My goal is to find something like 'b1234' in a paragraph and replace it with:

<a href=http://bugtracker.com/bug/1234>b1234</a>

I made this using plain ruby:

"I fixed b1234 today".gsub(/(b([0-9]+))/i, '<a href=http://bugtracker.com/bug/\2>\1</a>')

It outputs:

=> "I fixed <a href=http://bugtracker.com/bug/1234>b1234</a> today" 

I have the following in my rails view:

<%= post.content %>

Note: I don't store the HTML link code in my DB when posts are created.

If I do:

<%= post.content.gsub(...) %>

I get escaped html in the output file:

&lt;a href= ... instead of <a href= ...

...And I want that behavior, I don't want users posting HTML (iframes would be scary!).

But, how I can I still get the find and replace functionality I want without sacrificing security? Maybe a Javascript approach?

Thanks!

like image 735
cnandreu Avatar asked Oct 08 '22 16:10

cnandreu


1 Answers

Double up the equals signs. <%== post.content.gsub(...) %>. If users are also potentially writing HTML in this content, then you'll need to Sanitize it, so that only specified HTML tags are permitted, for example.

EDIT | Actually, provided the search string you are replacing does not contain HTML special characters, you can just escape the string, then do the gsub:

<%== h(post.content).gsub(...) %>
like image 69
d11wtq Avatar answered Oct 12 '22 10:10

d11wtq