Skip to content

Instantly share code, notes, and snippets.

@leonid-shevtsov
Created November 25, 2011 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonid-shevtsov/1394229 to your computer and use it in GitHub Desktop.
Save leonid-shevtsov/1394229 to your computer and use it in GitHub Desktop.
require 'cgi'
require 'nokogiri'
def escape_pres(text)
doc = Nokogiri::HTML(text)
pres = doc.css('pre').select do |pre|
# Select only PREs that don't have PREs as parents
# Slow but works
tag = pre.parent
while !tag.is_a?(Nokogiri::XML::Document) && tag.name!='pre'
tag = tag.parent
end
tag.is_a?(Nokogiri::XML::Document)
end
pres.each do |pre|
pre.children = pre.children.map {|node|
if node.name=='code'
node.children = CGI.escapeHTML(node.children.to_html)
node.to_html
else
CGI.escapeHTML(node.to_html)
end
}.join('')
end
doc.to_html
end
load 'escape_pres.rb'
describe 'The escape_pres function' do
it 'should escape tags within PRE tag' do
result = escape_pres('<pre><br></pre>')
result.should include '&lt;br&gt;'
end
it 'should not escape tags outside of PRE tags' do
result = escape_pres('<pre></pre><br>')
result.should include '<br>'
end
it 'should escape PRE tags within PRE tags' do
result = escape_pres('<pre><pre></pre></pre>')
result.should include '&lt;pre&gt;'
end
it 'should not escape CODE tags within PRE tags' do
result = escape_pres('<pre><code><br></code></pre>')
result.should include '<code>'
result.should include '&lt;br&gt;'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment