Skip to content

Commit

Permalink
Use 1.9 native XML escaping to speed up html_escape and shush regexp …
Browse files Browse the repository at this point in the history
…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)
  • Loading branch information
jeremy authored and kennyj committed Mar 7, 2012
1 parent 54621f7 commit 7cdfd91
Showing 1 changed file with 36 additions and 15 deletions.
51 changes: 36 additions & 15 deletions activesupport/lib/active_support/core_ext/string/output_safety.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,42 @@ module Util
HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;' }
JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' }

# A utility method for escaping HTML tag characters.
# This method is also aliased as <tt>h</tt>.
#
# 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 &gt; 0 &amp; a &lt; 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 '"&gt;&lt;&amp;&quot;"' == ('><&"'.encode('utf-8', :xml => :attr) rescue false)
# A utility method for escaping HTML tag characters.
# This method is also aliased as <tt>h</tt>.
#
# 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 &gt; 0 &amp; a &lt; 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 <tt>h</tt>.
#
# 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 &gt; 0 &amp; a &lt; 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

Expand Down

0 comments on commit 7cdfd91

Please sign in to comment.