Skip to content

Instantly share code, notes, and snippets.

@cristibalan
Created January 25, 2011 04:03
Show Gist options
  • Save cristibalan/794490 to your computer and use it in GitHub Desktop.
Save cristibalan/794490 to your computer and use it in GitHub Desktop.
module HamlJs
class Filter
def initialize(app)
@app = app
end
def call(env)
dup._call(env)
end
def _call(env)
template_root = Rails.root.join("app/js/templates")
output_root = Rails.root.join("public/javascripts/templates")
(Dir["#{template_root}/*.haml"] + Dir["#{template_root}/**/*.haml"]).each do |file|
file = File.expand_path(file)
basename = File.basename(file, ".haml")
var_name = basename
output_file = "#{var_name}.js"
dir = File.dirname(file.gsub("#{template_root}/", ""))
dir = "" if dir == "."
if dir != ""
output_file = "#{dir}/#{output_file}"
var_name = "#{dir.gsub("/", "_")}_#{var_name}"
end
output_file = File.join(output_root, output_file)
FileUtils.mkdir_p(File.dirname(output_file))
next unless dirty?(file, output_file)
File.open(output_file, "w") do |f|
f.puts "template_#{var_name} = #{compile(File.read(file)).to_json};"
end
end
@app.call env
end
private
def dirty?(from, to)
File.exist?(from) && (!File.exist?(to) || File.mtime(to) < File.mtime(from))
end
def compile(script)
command = "/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc"
f = Tempfile.open("hamljs.js")
f.puts "load('resources/haml.js');"
f.puts compile_js(script)
f.close
execute("#{command} #{f.path}")
ensure
f.close! if f
end
def compile_js(script)
<<-JS
try {
print('+' + Haml.optimize(Haml.compile(#{script.to_json})));
} catch (e) {
print('-' + e);
}
JS
end
def execute(command)
out = `#{command}`.chomp
if $?.success?
status, result = out[0, 1], out[1..-1]
if status == "+"
result
else
raise result[/^(?:Error: )?(.*)/, 1]
end
else
raise out
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment