Merge pull request #266 from bhollis/master

Extension that will pre-Gzip JS and CSS files
This commit is contained in:
Thomas Reynolds 2012-03-04 22:44:31 -08:00
commit b6415909dc
7 changed files with 85 additions and 1 deletions

View file

@ -0,0 +1,21 @@
Feature: GZIP assets during build
Scenario: Built assets should be gzipped
Given a successfully built app at "gzip-app"
Then the following files should exist:
| build/javascripts/test.js.gz |
| build/stylesheets/test.css.gz |
| build/index.html.gz |
| build/javascripts/test.js |
| build/stylesheets/test.css |
| build/index.html |
When I run `file build/javascripts/test.js.gz`
Then the output should contain "gzip"
Scenario: Preview server doesn't change
Given the Server is running at "gzip-app"
When I go to "/javascripts/test.js"
Then I should see "test_function"
When I go to "/stylesheets/test.css"
Then I should see "test_selector"

View file

@ -0,0 +1 @@
activate :gzip_assets

View file

@ -0,0 +1 @@
function test_function() {}

View file

@ -0,0 +1 @@
test_selector {}

View file

@ -40,6 +40,9 @@ module Middleman
# MinifyJavascript uses the YUI compressor to shrink JS files
autoload :MinifyJavascript, "middleman-more/extensions/minify_javascript"
# GZIP assets during build
autoload :GzipAssets, "middleman-more/extensions/gzip_assets"
end
# Setup renderers
@ -65,4 +68,6 @@ module Middleman
::Middleman::Extensions::MinifyJavascript }
Extensions.register(:relative_assets) {
::Middleman::Extensions::RelativeAssets }
end
Extensions.register(:gzip_assets) {
::Middleman::Extensions::GzipAssets }
end

View file

@ -0,0 +1,55 @@
require 'zlib'
require 'stringio'
require 'find'
module Middleman::Extensions
# This extension Gzips assets when building.
# Gzipped assets can be served directly by Apache or
# Nginx with the proper configuration, and pre-zipping means that we
# can use a more agressive compression level at no CPU cost per request.
#
# Use Nginx's gzip_static directive, or AddEncoding and mod_rewrite in Apache
# to serve your Gzipped files whenever the normal (non-.gz) filename is requested.
#
# Pass the :exts options to customize which file extensions get zipped (defaults
# to .html, .htm, .js and .css.
#
module GzipAssets
class << self
def registered(app, options={})
exts = options[:exts] || %w(.js .css .html .htm)
app.send :include, InstanceMethods
app.after_build do |builder|
Find.find(self.class.inst.build_dir) do |path|
next if File.directory? path
if exts.include? File.extname(path)
new_size = gzip_file(path, builder)
end
end
end
end
alias :included :registered
end
module InstanceMethods
def gzip_file(path, builder)
input_file = File.open(path, 'r').read
output_filename = path + '.gz'
File.open(output_filename, 'w') do |f|
gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)
gz.write input_file
gz.close
end
old_size = File.size(path)
new_size = File.size(output_filename)
builder.say_status :gzip, "#{output_filename} (#{old_size - new_size} bytes smaller)"
end
end
end
end