Created
November 25, 2011 19:07
-
-
Save leonid-shevtsov/1394229 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 '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 |
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
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 '<br>' | |
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 '<pre>' | |
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 '<br>' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment