Let escape_javascript handle conversion to string

This brings `escape_javascript` in line with the behavior of `json_escape` and
allows other value types to be output without needing explicit casting in the
view template.

Example:

    <%= javascript_tag do %>
      var locale = '<%== j I18n.locale %>'; // locale is a symbol
    <% end %>
This commit is contained in:
Andrew Vit 2018-08-09 02:26:46 -07:00
parent 0193b89be6
commit dd0cfb03b2
2 changed files with 9 additions and 4 deletions

@ -25,12 +25,13 @@ module JavaScriptHelper
#
# $('some_element').replaceWith('<%= j render 'some/element_template' %>');
def escape_javascript(javascript)
if javascript
result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) { |match| JS_ESCAPE_MAP[match] }
javascript.html_safe? ? result.html_safe : result
javascript = javascript.to_s
if javascript.empty?
result = ""
else
""
result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) { |match| JS_ESCAPE_MAP[match] }
end
javascript.html_safe? ? result.html_safe : result
end
alias_method :j, :escape_javascript

@ -23,6 +23,10 @@ def teardown
def test_escape_javascript
assert_equal "", escape_javascript(nil)
assert_equal "123", escape_javascript(123)
assert_equal "en", escape_javascript(:en)
assert_equal "false", escape_javascript(false)
assert_equal "true", escape_javascript(true)
assert_equal %(This \\"thing\\" is really\\n netos\\'), escape_javascript(%(This "thing" is really\n netos'))
assert_equal %(backslash\\\\test), escape_javascript(%(backslash\\test))
assert_equal %(dont <\\/close> tags), escape_javascript(%(dont </close> tags))