From 63cd9432265a32d222353b535d60333c2a6a5125 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 11 Dec 2011 15:30:05 -0700 Subject: Use 1.9 native XML escaping to speed up html_escape and shush regexp warnings length user system total real before 6 0.010000 0.000000 0.010000 ( 0.012378) after 6 0.010000 0.000000 0.010000 ( 0.012866) before 60 0.040000 0.000000 0.040000 ( 0.046273) after 60 0.040000 0.000000 0.040000 ( 0.036421) before 600 0.390000 0.000000 0.390000 ( 0.390670) after 600 0.210000 0.000000 0.210000 ( 0.209094) before 6000 3.750000 0.000000 3.750000 ( 3.751008) after 6000 1.860000 0.000000 1.860000 ( 1.857901) --- .../core_ext/string/output_safety.rb | 51 +++++++++++++++------- 1 file changed, 36 insertions(+), 15 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index 7b359a039b..c58ea16b44 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -6,21 +6,42 @@ class ERB HTML_ESCAPE = { '&' => '&', '>' => '>', '<' => '<', '"' => '"' } JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' } - # A utility method for escaping HTML tag characters. - # This method is also aliased as h. - # - # In your ERB templates, use this method to escape any unsafe content. For example: - # <%=h @person.name %> - # - # ==== Example: - # puts html_escape("is a > 0 & a < 10?") - # # => is a > 0 & a < 10? - def html_escape(s) - s = s.to_s - if s.html_safe? - s - else - s.gsub(/[&"><]/n) { |special| HTML_ESCAPE[special] }.html_safe + # Detect whether 1.9 can transcode with XML escaping. + if '"><&""' == ('><&"'.encode('utf-8', :xml => :attr) rescue false) + # A utility method for escaping HTML tag characters. + # This method is also aliased as h. + # + # In your ERB templates, use this method to escape any unsafe content. For example: + # <%=h @person.name %> + # + # ==== Example: + # puts html_escape("is a > 0 & a < 10?") + # # => is a > 0 & a < 10? + def html_escape(s) + s = s.to_s + if s.html_safe? + s + else + s.encode(s.encoding, :xml => :attr)[1...-1].html_safe + end + end + else + # A utility method for escaping HTML tag characters. + # This method is also aliased as h. + # + # In your ERB templates, use this method to escape any unsafe content. For example: + # <%=h @person.name %> + # + # ==== Example: + # puts html_escape("is a > 0 & a < 10?") + # # => is a > 0 & a < 10? + def html_escape(s) + s = s.to_s + if s.html_safe? + s + else + s.gsub(/[&"><]/n) { |special| HTML_ESCAPE[special] }.html_safe + end end end -- cgit v1.2.3