aboutsummaryrefslogtreecommitdiffstats
path: root/actionview
diff options
context:
space:
mode:
authorAndrew Vit <andrew@avit.ca>2018-08-09 02:26:46 -0700
committerAndrew Vit <andrew@avit.ca>2018-09-21 12:30:40 -0700
commitdd0cfb03b233e23b13e087f1cd39169b1ff6d936 (patch)
tree32754939d03b01d8cb33c6110bef31465f3f3301 /actionview
parent0193b89be6827fb6aa20f83af164901dc3e31590 (diff)
downloadrails-dd0cfb03b233e23b13e087f1cd39169b1ff6d936.tar.gz
rails-dd0cfb03b233e23b13e087f1cd39169b1ff6d936.tar.bz2
rails-dd0cfb03b233e23b13e087f1cd39169b1ff6d936.zip
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 %>
Diffstat (limited to 'actionview')
-rw-r--r--actionview/lib/action_view/helpers/javascript_helper.rb9
-rw-r--r--actionview/test/template/javascript_helper_test.rb4
2 files changed, 9 insertions, 4 deletions
diff --git a/actionview/lib/action_view/helpers/javascript_helper.rb b/actionview/lib/action_view/helpers/javascript_helper.rb
index 830088bea3..f80d0bd4ed 100644
--- a/actionview/lib/action_view/helpers/javascript_helper.rb
+++ b/actionview/lib/action_view/helpers/javascript_helper.rb
@@ -25,12 +25,13 @@ module ActionView
#
# $('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
diff --git a/actionview/test/template/javascript_helper_test.rb b/actionview/test/template/javascript_helper_test.rb
index a72bc6c2fe..80de541bf1 100644
--- a/actionview/test/template/javascript_helper_test.rb
+++ b/actionview/test/template/javascript_helper_test.rb
@@ -23,6 +23,10 @@ class JavaScriptHelperTest < ActionView::TestCase
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))