Sha256: cf36c263a624766badaa662dc8513d970657ab7461b59715c0dbbbe2ac4973fe

Contents?: true

Size: 1.79 KB

Versions: 12

Compression:

Stored size: 1.79 KB

Contents

require 'nokogiri'

module Govspeak
  class PostProcessor
    attr_reader :input

    @@extensions = []

    def initialize(html)
      @input = html
    end

    def nokogiri_document
      doc = Nokogiri::HTML::Document.new
      doc.encoding = "UTF-8"
      doc.fragment(input)
    end
    private :nokogiri_document

    def self.process(html)
      new(html).output
    end

    def self.extension(title, &block)
      @@extensions << [title, block]
    end

    def output
      document = nokogiri_document
      @@extensions.each do |_, block|
        instance_exec(document, &block)
      end
      document.to_html
    end

    extension("add class to last p of blockquote") do |document|
      document.css("blockquote p:last-child").map do |el|
        el[:class] = "last-child"
      end
    end

    # This "fix" here is tied into the rendering of images as one of the
    # pre-processor tasks. As images can be created inside block level elements
    # it's possible that their block level elements can be HTML entity escaped
    # to produce "valid" HTML.
    #
    # This sucks for us as we spit the user out HTML elements.
    #
    # This fix reverses this, and of course, totally sucks because it's tightly
    # coupled to the `render_image` code and it really isn't cool to undo HTML
    # entity encoding.
    extension("fix image attachment escaping") do |document|
      document.css("figure.image").map do |el|
        xml = el.children.to_s
        next unless xml =~ /&lt;div class="img"&gt;|&lt;figcaption&gt;/
        el.children = xml
          .gsub(
            %r{&lt;(div class="img")&gt;(.*?)&lt;(/div)&gt;},
            "<\\1>\\2<\\3>"
          )
          .gsub(
            %r{&lt;(figcaption)&gt;(.*?)&lt;(/figcaption&)gt;},
            "<\\1>\\2<\\3>"
          )
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
govspeak-5.6.0 lib/govspeak/post_processor.rb
govspeak-5.5.0 lib/govspeak/post_processor.rb
govspeak-5.4.0 lib/govspeak/post_processor.rb
govspeak-5.3.0 lib/govspeak/post_processor.rb
govspeak-5.2.2 lib/govspeak/post_processor.rb
govspeak-5.2.1 lib/govspeak/post_processor.rb
govspeak-5.2.0 lib/govspeak/post_processor.rb
govspeak-5.1.0 lib/govspeak/post_processor.rb
govspeak-5.0.3 lib/govspeak/post_processor.rb
govspeak-5.0.2 lib/govspeak/post_processor.rb
govspeak-5.0.1 lib/govspeak/post_processor.rb
govspeak-5.0.0 lib/govspeak/post_processor.rb