2012-02-11 05:09:39 +01:00
|
|
|
require 'zlib'
|
|
|
|
require 'stringio'
|
2012-03-05 01:42:14 +01:00
|
|
|
require 'find'
|
2012-02-11 05:09:39 +01:00
|
|
|
|
|
|
|
module Middleman::Extensions
|
|
|
|
|
2012-03-13 05:31:05 +01:00
|
|
|
# This extension Gzips assets and pages when building.
|
|
|
|
# Gzipped assets and pages can be served directly by Apache or
|
2012-02-11 05:09:39 +01:00
|
|
|
# Nginx with the proper configuration, and pre-zipping means that we
|
|
|
|
# can use a more agressive compression level at no CPU cost per request.
|
2012-02-11 09:22:10 +01:00
|
|
|
#
|
|
|
|
# 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
|
2012-03-05 01:42:14 +01:00
|
|
|
# to .html, .htm, .js and .css.
|
2012-02-11 09:22:10 +01:00
|
|
|
#
|
2012-03-13 05:31:05 +01:00
|
|
|
module Gzip
|
2012-02-11 05:09:39 +01:00
|
|
|
class << self
|
2012-02-11 09:22:10 +01:00
|
|
|
def registered(app, options={})
|
2012-03-05 01:42:14 +01:00
|
|
|
exts = options[:exts] || %w(.js .css .html .htm)
|
2012-02-11 09:22:10 +01:00
|
|
|
|
2012-03-05 01:42:14 +01:00
|
|
|
app.send :include, InstanceMethods
|
2012-02-11 05:09:39 +01:00
|
|
|
|
2012-03-05 01:42:14 +01:00
|
|
|
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)
|
2012-02-11 05:09:39 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2012-03-05 01:42:14 +01:00
|
|
|
|
2012-02-11 05:09:39 +01:00
|
|
|
alias :included :registered
|
|
|
|
end
|
|
|
|
|
2012-03-05 01:42:14 +01:00
|
|
|
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
|
2012-02-11 05:09:39 +01:00
|
|
|
end
|
|
|
|
|
2012-03-05 01:42:14 +01:00
|
|
|
old_size = File.size(path)
|
|
|
|
new_size = File.size(output_filename)
|
|
|
|
|
2012-03-11 19:06:48 +01:00
|
|
|
size_change_word = (old_size - new_size) > 0 ? 'smaller' : 'larger'
|
|
|
|
|
|
|
|
builder.say_status :gzip, "#{output_filename} (#{number_to_human_size((old_size - new_size).abs)} #{size_change_word})"
|
2012-02-11 05:09:39 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|