Skip to content

Instantly share code, notes, and snippets.

@pvasek
Created December 6, 2012 10:25
Show Gist options
  • Save pvasek/4223519 to your computer and use it in GitHub Desktop.
Save pvasek/4223519 to your computer and use it in GitHub Desktop.
Cassette coffee script compiler wrapper.
public class CoffeeScriptCachedCompiler : ICoffeeScriptCompiler
{
private readonly ICoffeeScriptCompiler _compiler;
public CoffeeScriptCachedCompiler(ICoffeeScriptCompiler compiler)
{
_compiler = compiler;
_hashFunction = MD5.Create();
}
public CompileResult Compile(string source, CompileContext context)
{
var key = context.SourceFilePath;
var hash = GetHash(source);
lock (_syncRoot)
{
Cached cachedVal;
if (_cache.TryGetValue(key, out cachedVal))
{
if (cachedVal.Hash == hash)
return cachedVal.Content;
_cache.Remove(key);
}
}
var content = _compiler.Compile(source, context);
var cached = new Cached { Content = content, Hash = hash };
lock (_syncRoot)
{
_cache.Add(key, cached);
}
return cached.Content;
}
private string GetHash(string content)
{
var hash = _hashFunction.ComputeHash(Encoding.Unicode.GetBytes(content));
return Convert.ToBase64String(hash);
}
private static readonly object _syncRoot = new object();
private static readonly Dictionary<string, Cached> _cache = new Dictionary<string, Cached>();
private readonly MD5 _hashFunction;
private class Cached
{
public CompileResult Content { get; set; }
public string Hash { get; set; }
}
}
public class CoffeeScriptOverrides : IConfiguration<TinyIoCContainer>
{
public void Configure(TinyIoCContainer container)
{
#if DEBUG
var compiler = container.Resolve<ICoffeeScriptCompiler>();
container.Register<ICoffeeScriptCompiler>(new CoffeeScriptCachedCompiler(compiler));
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment