HTML Escaping and Rails View Helpers
So I want to write a rails view helper which returns some nice html like this
<div> sandeep arneja </div>
This issue is that this rails helper has some html like div which should not be escaped and then the user's name sandeep which should be esacped as it comes from the user.
now rails has this thing built in to escape all data it outputs in the view. this is very useful for me. I am building an app very fast, i have tons of information coming from various sources and I dont have the resource to look and each of them and decide which need to be esacped. I like that any thing in the view which is like this, gets escaped.
<%= @user.name %>
We can have rails not escapee stuff we trust by saying
<%= raw @user.name %>
I don't want to do this for my reasoning above.
Another thing we can do is html_safe. We can call html_safe on our result in the view and that will mark the string safe and now rails will not escape it. This would work, but i dont want to mark the whole string as safe. The user name part still needs to be esacped.
So this is what i ended up doing
def my_name name = CGI.escapeHTML @user.name return "<div>"+name+"</div">.html_safe end
With this strategy:
the string is marked safe and rails wont escape it in the view
I have manually escaped the dangerous stuff before marking the whole returned result safe








