Skip to content

Instantly share code, notes, and snippets.

@freshtonic
Last active December 17, 2015 10:39
Show Gist options
  • Save freshtonic/5596722 to your computer and use it in GitHub Desktop.
Save freshtonic/5596722 to your computer and use it in GitHub Desktop.
The Rails Asset Pipeline & Angular JS partials.

My Angular.js partials live in public/partials.

In development mode I want them served from there, in production I want to have an Angular.js module called templates which simply popuates the template cache for me.

This isn't just about performance in production: it's making sure the partials are embedded in the assets which forces the partial's lifetime to be the same as the assets with no other caching worries when we redeploy the app.

<%# encoding:UTF-8 %>
<% environment.context_class.instance_eval { include ActionView::Helpers::JavaScriptHelper } %>
angular.module('templates', []).run([ '$templateCache', function($templateCache) {
<%# Only populate the template cache as the Asset pipeline is being built. #%>
<%# In other environments we'll just end up loading the partials directly. #%>
<%# The run() function will just be a no-op. #%>
<% if Rails.env.production? %>
<% Dir.glob(File.join('public', 'partials', '**', '*.html')).each do |f| %>
$templateCache.put("<%= f.gsub(/^public\//,"/") %>", "<%= escape_javascript(File.read(f)) %>" );
<% end %>
<% end %>
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment