Skip to content

Instantly share code, notes, and snippets.

@chrislloyd
Created October 14, 2010 21:54
Show Gist options
  • Save chrislloyd/627141 to your computer and use it in GitHub Desktop.
Save chrislloyd/627141 to your computer and use it in GitHub Desktop.
## Juggle
#
# The refined way of combining gathering client-side javascripts.
#
# usage:
# (in your Rakefile)
#
# require './lib/juggle'
# Juggle.file 'public/app.js' => 'public/libs.js' do
# curl 'http://github.com/documentcloud/underscore/raw/1.1.1/underscore.js'
# curl 'http://github.com/documentcloud/backbone/raw/master/backbone.js'
# curl 'http://github.com/janl/mustache.js/raw/0.3.0/mustache.js'
# file 'public/libs.js'
# coffee 'app/main.coffee'
# end
#
# This produces `public/app.js` and also a `public/app.min.js`.
#
# good practice:
#
# require 'rake/clean'
# CLOBBER.add 'public/*.js'
#
require 'closure-compiler'
class Juggle
attr_accessor :buffer
def self.compiler
@compiler ||= Closure::Compiler.new
end
def self.file(*args, &blk)
Kernel.send(:task, *args) do |task|
j = new
j.instance_eval &blk
j.write(task.name)
end
end
def initialize
self.buffer = []
end
def curl(url)
self.buffer << [url, `curl --silent #{url}`]
end
def coffee(path)
self.buffer << [path, `coffee --print #{path}`]
end
def file(path)
self.buffer << [path, File.read(path)]
end
def write(file)
File.open(file, 'w') {|f| f.puts js}
File.open(minified_name(file), 'w') {|f| f.puts minified_js}
end
private
def js
buffer.
map {|output| "// #{output.first}\n\n#{output.last}"}.
join("\n")
end
def minified_js
self.class.compiler.compile js
end
def minified_name(file)
File.join File.dirname(file),
[File.basename(file, '.*'), '.min', File.extname(file)].join
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment