Sha256: ce8dd05e1c25a1f3e1d1c47584c75a4e6cccb6447e2022b64909f4738dfcb333

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

require 'nokogiri'
require 'erubis'
require 'cgi'

module Deface
  class Parser
    # converts erb to markup
    #
    def self.erb_markup!(source)
      replacements = [ {"<%=" => "<code erb-loud>"},
                       {"<%"  => "<code erb-silent>"},
                       {"%>"  => "</code>"} ]

      replacements.each{ |h| h.each { |replace, with| source.gsub! replace, with } }

      source.scan(/(<code.*?>)((?:(?!<\/code>)[\s\S])*)(<\/code>)/).each do |match|
        source.gsub!("#{match[0]}#{match[1]}#{match[2]}", "#{match[0]}#{CGI.escapeHTML(match[1])}#{match[2]}")
      end

      source
    end

    # undoes ERB markup generated by Deface::Parser::ERB
    #
    def self.undo_erb_markup!(source)
      replacements = [ {"<code erb-silent>" => '<%'},
                       {"<code erb-loud>"   => '<%='},
                       {"</code>"           => '%>'},
                       {/(<|&lt;)code(\s|%20)erb-silent(&gt;|>)/ => '<%'},
                       {/(<|&lt;)code(\s|%20)erb-loud(&gt;|>)/   => '<%='},
                       {/(<|&lt;)\/code(&gt;|>)/                 => '%>'} ]

      replacements.each{ |h| h.each { |replace, with| source.gsub! replace, with } }

      #un-escape changes from Nokogiri and erb-markup!
      source.scan(/(<%.*?)((?:(?!%>)[\s\S])*)(%>)/).each do |match|
        escaped = URI.unescape match[1]
        escaped = CGI.unescapeHTML CGI.unescapeHTML(escaped)
        source.gsub!("#{match[0]}#{match[1]}#{match[2]}", "#{match[0]}#{escaped}#{match[2]}")
      end

      source
    end

    def self.convert(source)
      erb_markup!(source)

      if source =~ /(<html.*?)((?:(?!>)[\s\S])*)(>)/
        Nokogiri::HTML::Document.parse(source)
      else
        Nokogiri::HTML::DocumentFragment.parse(source)
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
deface-0.3.0 lib/deface/parser.rb