Created
November 2, 2009 13:59
-
-
Save oleganza/224174 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'strscan' | |
require 'cgi' | |
module HTMLEscaper | |
ENTITIES = { | |
"<" => "<", | |
">" => ">", | |
'"' => """, | |
'&' => "&" | |
} | |
AT = "@" | |
PROTO = "://" | |
MAILTO = "mailto:" | |
def self.escape(str) | |
scanner = StringScanner.new(str) | |
buffer = "" | |
while 1 | |
return buffer if scanner.eos? | |
if s = scanner.scan_until(%r{[<>"&]|[\w\+\-_]+://|\w[\.\w]*@}um) | |
m = scanner.matched | |
l = m.size | |
r = 0..(-1 - l) | |
buffer << s[r] | |
if l == 1 # entity | |
buffer << ENTITIES[m] | |
else # url | |
url = m.dup | |
if s = scanner.scan(%r{[\w&\.,%;:_/\-\?\[\]=@]+[\w/]}um) | |
url << s | |
end | |
buffer << (block_given? && yield(url) || begin | |
url = CGI::escapeHTML(url) | |
pfx = nil | |
if url[AT] && !url[PROTO] | |
pfx = MAILTO | |
end | |
%{<a href="#{pfx}#{url}">#{url}</a>} | |
end) | |
end | |
else | |
buffer << scanner.rest | |
return buffer | |
end | |
end | |
end | |
end | |
if $0 == __FILE__ | |
escaped = HTMLEscaper.escape( %{ | |
a & "b" <> c | |
[email protected], tell me one thing! | |
ssh://[email protected] | |
Look here git+ssh://[email protected]:blah/blah.git: | |
<git+ssh://[email protected]:blah/blah.git>: | |
<a class="class" href="http://example.com/?a=b&c=d">"hello"</a> | |
<http://example.com/?> | |
<http://example.com/?abc> | |
(http://example.com)(blah) | |
<http://example.com/?blah&ersand=1> | |
<http://example.com/?blah&> | |
}) do |url| | |
puts "Ping url #{url}" | |
url = CGI::escapeHTML(url) | |
%{[A HREF="#{url}"]#{url}[/A]} | |
nil | |
end | |
puts escaped | |
# Output as of November 2, 2009 (14:58) | |
# | |
# a & "b" <> c | |
# | |
# <a href="mailto:[email protected]">[email protected]</a>, tell me one thing! | |
# <a href="ssh://[email protected]">ssh://[email protected]</a> | |
# | |
# Look here <a href="git+ssh://[email protected]:blah/blah.git">git+ssh://[email protected]:blah/blah.git</a>: | |
# | |
# <<a href="git+ssh://[email protected]:blah/blah.git">git+ssh://[email protected]:blah/blah.git</a>>: | |
# | |
# <a class="class" href="<a href="http://example.com/?a=b&c=d">http://example.com/?a=b&c=d</a>">"hello"</a> | |
# <<a href="http://example.com/">http://example.com/</a>?> | |
# <<a href="http://example.com/?abc">http://example.com/?abc</a>> | |
# (<a href="http://example.com">http://example.com</a>)(blah) | |
# <<a href="http://example.com/?blah&ampersand=1">http://example.com/?blah&ampersand=1</a>> | |
# <<a href="http://example.com/?blah">http://example.com/?blah</a>&> | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment