Sha256: 86d7b1db46e566219cda78a64be26d4bb8ae5f2d38f77e32af438923ec8710d2

Contents?: true

Size: 1.1 KB

Versions: 1

Compression:

Stored size: 1.1 KB

Contents

require "digest/md5"
require "rack"
require "yui/compressor"

class Hork
  VERSION = "1.0.0"

  attr_reader :app, :css_compressor, :js_compressor, :compressed_files

  def initialize(app)
    @app              = app
    @css_compressor   = YUI::CssCompressor.new
    @js_compressor    = YUI::JavaScriptCompressor.new(:munge => true)
    @compressed_files = {}
  end

  def call(env)
    status, headers, body = response = app.call(env)

    case headers["Content-Type"]
    when /\bcss\b/        then compress_response(:css, *response)
    when /\bjavascript\b/ then compress_response(:js,  *response)
    else response
    end
  end

  def compress_response(type, status, headers, body)
    compressed_body = compress(type, read_body(body))
    headers["Content-Length"] = Rack::Utils.bytesize(compressed_body).to_s
    [status, headers, [compressed_body]]
  end

  def compress(type, source)
    compressed_files[Digest::MD5.hexdigest(source)] ||=
      send("#{type}_compressor").compress(source)
  end

  def read_body(source_body)
    "".tap do |body|
      source_body.each { |part| body << part }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hork-1.0.0 lib/hork.rb