middleman/middleman-more/lib/middleman-more/extensions/minify_javascript.rb

77 lines
2 KiB
Ruby
Raw Normal View History

2011-12-31 23:28:17 +01:00
# Extension namespace
module Middleman::Extensions
2011-12-31 23:28:17 +01:00
# Minify Javascript Extension
module MinifyJavascript
2011-12-31 23:28:17 +01:00
# Setup extension
class << self
2011-12-31 23:28:17 +01:00
# Once registered
def registered(app)
2011-12-31 23:28:17 +01:00
# Once config is parsed
app.after_configuration do
2011-12-31 23:28:17 +01:00
# Tell sprockets which compressor to use
if !js_compressor
require 'uglifier'
set :js_compressor, ::Uglifier.new
end
2011-12-31 23:28:17 +01:00
# Setup Rack to watch for inline JS
use InlineJavascriptRack, :compressor => js_compressor
end
end
alias :included :registered
end
2011-12-31 23:28:17 +01:00
# Rack middleware to look for JS in HTML and compress it
class InlineJavascriptRack
2011-12-31 23:28:17 +01:00
# Init
# @param [Class] app
# @param [Hash] options
def initialize(app, options={})
@app = app
@compressor = options[:compressor]
end
2011-12-31 23:28:17 +01:00
# Rack interface
# @param [Rack::Environmemt] env
# @return [Array]
def call(env)
status, headers, response = @app.call(env)
if env["PATH_INFO"].match(/\.html$/)
uncompressed_source = case(response)
when String
response
when Array
response.join
when Rack::Response
response.body.join
when Rack::File
File.read(response.path)
end
minified = uncompressed_source.gsub(/(<scri.*?\/\/<!\[CDATA\[\n)(.*?)(\/\/\]\].*?<\/script>)/m) do |m|
first = $1
uncompressed_source = $2
last = $3
2011-12-12 23:20:20 +01:00
minified_js = @compressor.compress(uncompressed_source)
first << minified_js << "\n" << last
end
headers["Content-Length"] = ::Rack::Utils.bytesize(minified).to_s
response = [minified]
end
[status, headers, response]
end
end
end
2011-12-31 23:28:17 +01:00
# Register extension
# register :minify_javascript, MinifyJavascript
end