Skip to content

Instantly share code, notes, and snippets.

@izelnakri
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save izelnakri/919c303cd70e678b0316 to your computer and use it in GitHub Desktop.

Select an option

Save izelnakri/919c303cd70e678b0316 to your computer and use it in GitHub Desktop.
My Auto-minification code for JS templates on Rails!
#on "config/environments/development.rb"
#fixes display:inline-block positioning problems with whitespaced HTML
#reduces JS template filesize
#introduces a convention to use //= require_tree ./templates/compiled on application.coffee
#requires listen gem v2 + htmlcompressor
Rails.application.configure do
#development.rb defaults...
config.after_initialize do
def create_compiled_js_template(item)
unless File.directory?(item) #necessary for the dir.glob at start
rel_path = item.sub("#{root}/app/assets/javascripts/templates/", "")
compile_dir = "#{root}/app/assets/javascripts/templates/compiled/#{rel_path}"
dirname = File.dirname(compile_dir)
unless File.directory?(dirname)
FileUtils.mkdir_p(dirname)
end
compressor = HtmlCompressor::Compressor.new(:remove_intertag_spaces => true)
new_file = compressor.compress(File.read(item))
IO.write(compile_dir, new_file)
puts "Template compiled"
end
end
Dir.glob("#{Rails.root}/app/assets/javascripts/templates/**/*") do |item|
unless item.scan("compiled")[0] #means its compiled dir
create_compiled_js_template(item)
end
end
#ONLY BUG: IT DOESN'T DELETE DIRECTORIES + FILES ON START
#+ DOESN'T DELETE DIR WHILE IT RUNS
listener = Listen.to("app/assets/javascripts/templates", ignore: %r{^(?: compiled )(/|$)}x) do |modified, added, removed|
if modified[0]
puts "MODIFIED - #{modified[0]}"
create_compiled_js_template(modified[0])
elsif added[0]
puts "ADDED - #{added[0]}"
create_compiled_js_template(added[0])
elsif removed[0]
puts "DELETED - #{removed[0]}"
rel_path = removed[0].sub("#{root}/app/assets/javascripts/templates/", "")
File.delete("#{root}/app/assets/javascripts/templates/compiled/#{rel_path}")
puts "Compiled template removed"
end
end
listener.start
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment