Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • raw vs. html_safe vs. h to unescape html

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 1.84k
    Comment on it

    Rails has a nice way to protect yourself from CSRF attacks through threatening HTML encoding from anything you write between <%= %>. But there is a caution, you want to render HTML from string so you need to tell rails that it should not escape your HTML in that case.

    There are 3 methods to unescape html and they are:

    1. raw
    2. html_safe
    3. h

    raw and html_safe are same means they mark the string as safe and rails will not encode it anymore. There is no difference between the two. So how we should take the decision that in which particular case we should use which particular method, so the idea is like if the string is nil. html_safe will break since there would not be .html_safe on nil it will raise an exception so you should use raw in that case.

    h() is like short form for the method html_escape.

    h can only be used within a controller or a view since it is from a helper it's a method that basically convert things like < and > into number characters so that rendering won't break your html.

    These two calls are substitutes:

    <%=h user.last_name %>
    <%= h(user.last_name) %>
    

    raw is actually substitute to calling to_s chained with html_safe on it, but is declared on a helper, like h, so it can only be used on controllers and views.

    The difference between Rails html_safe() and raw() is described below:

    def raw(stringish)
    
      stringish.to_s.html_safe
    
    end
    

    Yes absolutely, raw() is a wrapper around html_safe() which drives the input to String and then calls html_safe() on it. In other words we can say that raw() is a helper in a module while html_safe() is a method on the String class.

    So use these 3 functions wisely and make the content html safe so that nobody can inject malicious code or JavaScript into it.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: