Skip to content

Commit c32ed89

Browse files
committed
Added helper from rails 3-2-stable for escaping javascript
1 parent 8282ada commit c32ed89

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

lib/gon/helpers.rb

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ def include_gon(options = {})
1010
if Gon.request_env && Gon.all_variables.present? && Gon.request == request.object_id
1111
data = Gon.all_variables
1212
namespace = options[:namespace] || 'gon'
13-
script = '<script>window.' + namespace + ' = {};'
13+
start = '<script>window.' + namespace + ' = {};'
14+
script = ''
1415
if options[:camel_case]
1516
data.each do |key, val|
1617
script << namespace + '.' + key.to_s.camelize(:lower) + '=' + val.to_json + ';'
@@ -20,12 +21,48 @@ def include_gon(options = {})
2021
script << namespace + '.' + key.to_s + '=' + val.to_json + ';'
2122
end
2223
end
23-
script << '</script>'
24+
script = start + escape_javascript(script) + '</script>'
2425
script.html_safe
2526
else
2627
""
2728
end
2829
end
30+
31+
unless self.respond_to? :escape_javascript
32+
# Just add helper from rails 3-2-stable
33+
34+
JS_ESCAPE_MAP = {
35+
'\\' => '\\\\',
36+
'</' => '<\/',
37+
"\r\n" => '\n',
38+
"\n" => '\n',
39+
"\r" => '\n',
40+
'"' => '\\"',
41+
"'" => "\\'"
42+
}
43+
44+
if "ruby".encoding_aware?
45+
JS_ESCAPE_MAP["\342\200\250".force_encoding('UTF-8').encode!] = '&#x2028;'
46+
else
47+
JS_ESCAPE_MAP["\342\200\250"] = '&#x2028;'
48+
end
49+
50+
# Escapes carriage returns and single and double quotes for JavaScript segments.
51+
#
52+
# Also available through the alias j(). This is particularly helpful in JavaScript responses, like:
53+
#
54+
# $('some_element').replaceWith('<%=j render 'some/element_template' %>');
55+
def escape_javascript(javascript)
56+
if javascript
57+
result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] }
58+
javascript.html_safe? ? result.html_safe : result
59+
else
60+
''
61+
end
62+
end
63+
64+
alias_method :j, :escape_javascript
65+
end
2966
end
3067
end
3168

0 commit comments

Comments
 (0)