Skip to content

Instantly share code, notes, and snippets.

@krsmedlund
Last active October 3, 2015 02:28
Show Gist options
  • Save krsmedlund/2371968 to your computer and use it in GitHub Desktop.
Save krsmedlund/2371968 to your computer and use it in GitHub Desktop.
from compressor.filters import CompilerFilter
class CoffeeCompilerFinder(staticfiles.finders.AppDirectoriesFinder):
"""
A quick hacked up staticfiles-finder that will automatically recompile .coffee files to .js and serve the .js file
It will respond to a request for /foo/bar/baz.js and if the coffee-file with the same name in that same dir is newer then
then js-file requested then the js-file will be recompiled.
I did this to not have to manually recompile my scripts or use the watcher and still be compatible with require.js
without have to change the code once i deploy with compiled js-files. it depends on django-compressor at the moment
but if you dont use that its just a small class to lift out from it.
usage:
STATICFILES_FINDERS = (
'myapp.finders.CoffeeCompilerFinder',
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
include this finder *before* the default one else it will serve already compiled js!
"""
def find(self, path, all=False):
if not settings.DEBUG:
return []
matches = []
fname, orig_ext = os.path.splitext(path)
precompile_name = "%s.coffee" % (fname)
for app in self.apps:
match = self.find_in_app(app, precompile_name)
if match:
f_out, temp_ext = os.path.splitext(match)
match_outfile = "%s%s" % (f_out, orig_ext)
try:
if not os.path.exists(match_outfile) or os.path.getmtime(match) > os.path.getmtime(match_outfile):
CompilerFilter(content="", command='coffee --compile {infile}', filename=match).input()
return match_outfile
except Exception as e:
return []
return matches
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment