Skip to content

Instantly share code, notes, and snippets.

@oscherler
Created August 17, 2012 18:34
Show Gist options
  • Save oscherler/3381409 to your computer and use it in GitHub Desktop.
Save oscherler/3381409 to your computer and use it in GitHub Desktop.
Quick and dirty minified web service

Very quick and dirty modification of Ben Pickles' minify, moving the actual minification to a web service in case you already have a minification workflow in place but don't want to install java on your development virtual machine.

You need Ruby, gems sinatra and closure-compiler (and thus Java) on the machine that hosts the web service.

Start the web service with

ruby app.rb

On the machine that calls the web service, you need to set the environment variable MINIFY_HOST with the host and port of the web service:

export MINIFY_HOST=10.0.0.42:4567

Then

ruby minify.rb foo.js
require 'sinatra'
get '/' do
'Minify'
end
post '/' do
require 'closure-compiler'
request.body.rewind # in case someone already read it
data = request.body.read
result = Closure::Compiler.new.compile( data )
end
#!/usr/bin/env ruby
# Very quick and dirty modification of Ben Pickles' minify, moving the actual minification
# to a web service in case you already have a minification workflow in place but don't want
# to install java on your development virtual machine.
#
# Needs environment variable MINIFY_HOST with host and port:
#
# export MINIFY_HOST=10.0.0.42:4567
#
# http://benpickles.com/articles/47-minify-command-line-tool
dry_run = ARGV.delete('--dry-run')
force = ARGV.delete('--force')
if ARGV.empty?
puts <<-USAGE
minify, swiftly concat and minify JavaScript files from the command line
Pass a single argument to create a .min.js version:
$ minify jquery.myplugin.js
Pass one or more files to concat and minify them - the last argument is
always the output file:
$ minify input.js output.js
$ minify a.js few.js files.js output.min.js
If the output file already exists you can overwrite it by using the --force.
If you're not sure use --dry-run to see what'll happen.
USAGE
exit
end
input, output = ARGV.length == 1 ?
[ARGV, ARGV.first.sub(/\.js$/, '.min.js')] :
[ARGV[0..-2], ARGV.last]
if (missing = input.select { |path| !File.exists?(path) }).any?
puts "Some input files do not exist:\n #{missing.join(" \n")}"
exit 1
end
if File.exists?(output) && !force
puts "Output file #{output} already exists, use the --force to overwrite"
exit 1
end
if dry_run
puts "#{input.inspect} => #{output}"
else
require 'net/http'
host, port = ENV['MINIFY_HOST'].split(':')
request = Net::HTTP::Post.new( '/', initheader = { 'Content-Type' => 'text/javascript; charset=utf-8' } )
request.body = input.map { |file| File.read(file) }.join("\n")
response = Net::HTTP.new( host, port ).start { |http| http.request( request ) }
File.open(output, 'w') do |f|
f.write response.body
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment