0

I need help in displaying the output of a rails helper method inside the script tags in the application.html.erb layout file. I put the following code just before the closing html tag:

<script>
    App.ready = function() {
        App.initApp(jQuery.parseJSON("<%= current_user_json %>"));
    }
</script>

This current_user_json is a helper method that is in the application controller file.

The output the above code produces in the browser(view page source) is:

<script>
    App.ready = function() {
        App.initApp(jQuery.parseJSON("{&quot;id&quot;:3,&quot;email&quot;:&quot;user5@user.com&quot;,&quot;username&quot;:null}"));
    }
</script>

The proper output should be:

<script>
     App.ready = function() {
         App.initApp(jQuery.parseJSON('{"id":3,"email":"user5@user.com","username":null}'))
     }
</script>

If someone could help me out, I will really be relieved of this problem I am trying to resolve for the past couple of days.

codingbear
  • 296
  • 5
  • 18

2 Answers2

2

Change this:

<%= current_user_json %>

To this:

<%= current_user_json.html_safe %>

Heads up that you must ensure your json is properly escaped. For example, if your current_user_json happens to have a field with a quote in it, you must escape that quote. If you don't escape, then what you're doing is a pretty typical attack vector for hackers, so proceed with care.

joelparkerhenderson
  • 34,808
  • 19
  • 98
  • 119
  • Hi @joelparkerhenderson, thanks for the quick, helpful and precise response. I am not too familiar with 'attack vector'. Could you help me point to some resource online where I can read and understand more about them in order to protect the code from it. – codingbear Dec 24 '14 at 08:36
  • You're welcome. To understand more about the attack vector, the key idea is that you're mixing different types of strings, and some characters may have special meanings that interfere with some of the strings. Google for "Cross Site Request Forgery" and you'll see a lot of examples. – joelparkerhenderson Dec 24 '14 at 15:40
2

Try this

<%= raw current_user_json.to_json %>
pkrawat1
  • 671
  • 7
  • 18
  • Hi @pkrawat1 thanks for your amazing response, your answer would have been the correct one if the helper method wasn't set to output json. So cheers, and thanks once again. – codingbear Dec 24 '14 at 08:39