public
Created

Sprockets Closure Library Processor

  • Download Gist
Gemfile
Ruby
1 2 3
source :rubygems
gem 'rack'
gem 'sprockets', :git => 'git://github.com/sstephenson/sprockets.git'
config.ru
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
require 'sprockets'
require 'tilt'
 
# svn checkout http://closure-library.googlecode.com/svn/trunk/ closure-library
ClosureLibrary = File.expand_path("../closure-library", __FILE__)
 
class ClosureDependenciesProcessor < Tilt::Template
def prepare; end
 
def evaluate(context, locals, &block)
# METHOD 1: Shell out to calcdeps
# calcdeps(file).each do |path|
# context.require_asset(path)
# end
 
# METHOD 2: Extract goog.require statments and guess filename
# Much faster, but I don't know about closure lib to know
# that its reilable.
data.lines.each do |line|
if line =~ /goog\.require\s*\(\s*[\'\"]([^\)]+)[\'\"]\s*\)/
goog, mod, sub = $1.split(".")
sub ||= mod
mod, sub = mod.downcase, sub.downcase
dep = [goog, mod, sub].join("/")
context.require_asset(dep)
end
end
 
data
end
 
def calcdeps(path)
bin = File.join(ClosureLibrary, "closure/bin/calcdeps.py")
`#{bin} -i #{path} 2> /dev/null`.split("\n")
end
end
 
Assets = Sprockets::Environment.new do |env|
env.append_path "."
env.append_path File.join(ClosureLibrary, "closure")
env.register_preprocessor 'application/javascript', ClosureDependenciesProcessor
end
 
map "/assets" do
run Assets
end
 
map "/" do
run lambda { |env|
html = <<-HTML
<html>
<head>
<script src="/assets/hello.js"></script>
</head>
<body onload="sayHi()">
</body>
</html>
HTML
[200, {'Content-Type' => 'text/html'}, [html]]
}
end
hello.js
JavaScript
1 2 3 4 5 6
goog.require('goog.dom');
 
function sayHi() {
var newHeader = goog.dom.createDom('h1', {'style': 'background-color:#EEE'}, 'Hello world!');
goog.dom.appendChild(document.body, newHeader);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.