class Widont::Rack

Public Class Methods

new(app, options={}) click to toggle source
# File lib/middleman-widont.rb, line 15
def initialize(app, options={})
  @app = app
  @nbsp = options[:nbsp]
  @tags = options[:tags]
end

Public Instance Methods

call(env) click to toggle source
# File lib/middleman-widont.rb, line 21
def call(env)
  status, headers, response = @app.call(env)

  type = headers.fetch("Content-Type", "application/octet-stream").split(";").first
  path = env["PATH_INFO"]
  if %w[text/html application/xhtml+xml].include?(type)
    use_xml = type == "application/xhtml+xml"
    html = ::Middleman::Util.extract_response_text(response)
    html_doc = use_xml ? Nokogiri::XML(html) : Nokogiri::HTML(html)

    html_doc.css(@tags.join(", ")).each do |tag|
      content = tag.inner_html.strip
      index = content.rindex(/\s/)
      if index
        content[index] = @nbsp
        tag.inner_html = content
      end
    end
    response = use_xml ? html_doc.to_xml : html_doc.to_html
  end

  if response.is_a?(String)
    headers["Content-Length"] = ::Rack::Utils.bytesize(response).to_s
    response = [response]
  end

  [status, headers, response]
end