提交 dd0cfb03 编写于 作者: A Andrew Vit

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 %>
上级 0193b89b
......@@ -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))
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册