Skip to content

Instantly share code, notes, and snippets.

@nurse
Created March 14, 2009 08:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nurse/79019 to your computer and use it in GitHub Desktop.
Save nurse/79019 to your computer and use it in GitHub Desktop.
ALLOW_TAGS = %w/font span p b br/
def validate_xml_fragment
str = self
tags = str.scan(/\G(?:(<[^<>]+>)|[^<>&]+|[^&<>]*(?:&#?\w+;[^&<>]*)+)/)
return ERB::Util.html_escape(str) unless $'.empty?
stack = []
tags.each do |tag|
case tag.first
when /<(\w+)(?: +\w+=(?:"[^"]*"|'[^']*'|\w+))* *(\/)?>/
return ERB::Util.html_escape(str) unless ALLOW_TAGS.include?($1)
stack.push($1) unless $2
when /<\/(\w+)>/
return ERB::Util.html_escape(str) unless stack.last == $1
stack.pop
when nil
else
return ERB::Util.html_escape(str)
end
end
return ERB::Util.html_escape(str) unless stack.empty?
nil while str.gsub!(/^\s+|\s+$|\A<br *\/>|<br *\/>\z/, '')
str
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment