Skip to content

Instantly share code, notes, and snippets.

@tdg5
Created January 21, 2014 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdg5/8538521 to your computer and use it in GitHub Desktop.
Save tdg5/8538521 to your computer and use it in GitHub Desktop.
An ERB precompiled AngularJS service for Rails allowing easy access to HTML templates fingerprinted by the Asset Pipeline.
<%
# Generate lookup Hash of fingerprinted filenames for html templates
# Leave regexp open ended to include preprocessed templates (.erb, etc.)
template_regexp = /(?:\/assets\/templates\/)(.*\.html)/
template_files = Rails.application.assets.each_file.to_a.join("\n").scan(template_regexp).flatten
templates = Hash[template_files.map {|file| [file, asset_url(file)] }]
%>
var fingerprintedTemplates = angular.module('services.fingerprintedTemplates', []);
fingerprintedTemplates.factory('fingerprintedTemplates', [
'$q',
'$http',
'$templateCache',
function($q, $http, $templateCache) {
var templates = <%= templates.to_json %>;
return {
load: function(templatePath) {
var templateUrl = this.templateUrl(templatePath),
deferred = $q.defer();
$http.get(templateUrl, {cache: $templateCache}).success(function(response) {
return deffered.resolve(response);
});
return deferred.promise;
},
templateUrl: function(templatePath) {
var url = templates[templatePath];
if(!url) { throw 'Unknown fingerprinted template: ' + templatePath; }
return url;
}
};
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment