Smart default escaping of javascript in .js.erb templates

Hey there!

I find myself using remote: true on forms and rendering say create.js.erb in the xhr response quite a lot. The create.js.erb template would typically contain something like:

$(’.comments’).prepend(’<%= j render @comment %>’);

This gives me a lot of the niceties in Rails and a pretty snappy user experience. However, you must always remember to use escape_javascript / j in order to escape javascript properly/safely. This annoys me as it is not secure by default (hey if you forget to do it, most likely things will not work), like the html escaping is done for regular html templates.

But this is a .js.erb template, so Rails should know that anything coming from a <%= %> block needs to be properly escaped for javascript, just like everything just works for html templates.

So my question is, couldn’t it be possible to make something similar to the html_safe methods just for javascript and start escaping output for javascript by default in .js.erb templates? And possibly add similar default escaping for other kinds of templates if any?

Curious to hear what you think!

-Eirik