1
0
Fork 0
mirror of https://github.com/middleman/middleman.git synced 2022-11-09 12:20:27 -05:00
middleman--middleman/lib/middleman/features/minify_javascript.rb

43 lines
1.1 KiB
Ruby
Raw Normal View History

module Middleman::Features::MinifyJavascript
class << self
def registered(app)
2011-07-10 19:02:52 -04:00
require 'uglifier'
app.set :js_compressor, ::Uglifier.new
app.use InlineJavascriptRack
end
alias :included :registered
end
2011-07-10 19:02:52 -04:00
class InlineJavascriptRack
def initialize(app, options={})
@app = app
end
def call(env)
status, headers, response = @app.call(env)
if env["PATH_INFO"].match(/\.html$/)
compressor = ::Uglifier.new
2011-10-03 20:09:27 -04:00
if response.is_a?(::Rack::File)# or response.is_a?(::Sinatra::Helpers::StaticFile)
2011-07-10 19:02:52 -04:00
uncompressed_source = File.read(response.path)
else
uncompressed_source = response.join
end
minified = uncompressed_source.gsub(/(<scri.*?\/\/<!\[CDATA\[\n)(.*?)(\/\/\]\].*?<\/script>)/m) do |m|
first = $1
uncompressed_source = $2
last = $3
minified_js = compressor.compile(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