Skip to content

Commit

Permalink
Move escape_once logic to ERB::Util, where it belongs to
Browse files Browse the repository at this point in the history
All the logic is based on the HTML_ESCAPE constant available in
ERB::Util, so it seems more logic to have the entire method there and
just delegate the helper to use it.
  • Loading branch information
carlosantoniodasilva committed Feb 1, 2012
1 parent 0eb4673 commit 608eddc
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion actionpack/lib/action_view/helpers/tag_helper.rb
Expand Up @@ -118,7 +118,7 @@ def cdata_section(content)
# escape_once("<< Accept & Checkout")
# # => "<< Accept & Checkout"
def escape_once(html)
html.to_s.gsub(/[\"><]|&(?!([a-zA-Z]+|(#\d+));)/) { |special| ERB::Util::HTML_ESCAPE[special] }
ERB::Util.html_escape_once(html)
end

private
Expand Down
14 changes: 14 additions & 0 deletions actionpack/test/template/erb_util_test.rb
Expand Up @@ -44,4 +44,18 @@ def test_rest_in_ascii
assert_equal chr, html_escape(chr)
end
end

def test_html_escape_once
assert_equal '1 &lt; 2 &amp; 3', html_escape_once('1 < 2 &amp; 3')
end

def test_html_escape_once_returns_unsafe_strings_when_passed_unsafe_strings
value = html_escape_once('1 < 2 &amp; 3')
assert !value.html_safe?
end

def test_html_escape_once_returns_safe_strings_when_passed_safe_strings
value = html_escape_once('1 < 2 &amp; 3'.html_safe)
assert value.html_safe?
end
end
2 changes: 2 additions & 0 deletions activesupport/CHANGELOG.md
@@ -1,5 +1,7 @@
## Rails 4.0.0 (unreleased) ##

* Add html_escape_once to ERB::Util, and delegate escape_once tag helper to it. *Carlos Antonio da Silva*

* Remove ActiveSupport::TestCase#pending method, use `skip` instead. *Carlos Antonio da Silva*

* Deprecates the compatibility method Module#local_constant_names,
Expand Down
15 changes: 15 additions & 0 deletions activesupport/lib/active_support/core_ext/string/output_safety.rb
Expand Up @@ -33,6 +33,21 @@ def html_escape(s)
singleton_class.send(:remove_method, :html_escape)
module_function :html_escape

# Returns an escaped version of +html+ without affecting existing escaped entities.
#
# ==== Examples
# html_escape_once("1 < 2 &amp; 3")
# # => "1 &lt; 2 &amp; 3"
#
# html_escape_once("&lt;&lt; Accept & Checkout")
# # => "&lt;&lt; Accept &amp; Checkout"
def html_escape_once(s)
result = s.to_s.gsub(/[\"><]|&(?!([a-zA-Z]+|(#\d+));)/) { |special| HTML_ESCAPE[special] }
s.html_safe? ? result.html_safe : result
end

module_function :html_escape_once

# A utility method for escaping HTML entities in JSON strings
# using \uXXXX JavaScript escape sequences for string literals:
#
Expand Down

0 comments on commit 608eddc

Please sign in to comment.