Skip to content

Instantly share code, notes, and snippets.

@marcusmalmberg
Created November 14, 2012 18:30
Show Gist options
  • Save marcusmalmberg/4073878 to your computer and use it in GitHub Desktop.
Save marcusmalmberg/4073878 to your computer and use it in GitHub Desktop.
Easy way to have full control of asset precompilation

What is this?

It's a way to better handle page specific css and javascript files. It gives you full control of which files are included and compiled where. This is a way to easily minimize the file request while still keeping out unnecessary stuff from the files, without you as a developer need to edit environment files.

Why not controller specific files?

guides.rubyonrails.org mentions a way to easily handle controller specific stylesheets and javascript files. Like:

javascript_include_tag params[:controller]

Sometimes that's not enough or it will break because of some gem you have installed, and that's when this method comes in handy.

Wouldn't...?

Yes. You can instead of naming the files "_c" add each of them individually to the production.rb file and remove the regexp-thingy.

But...?

Sure. You could create a folder named e.g. "manifest" in your stylesheets folder and then have the pipeline to precompile all files in that directory. That might be prettier, but I extracted the current code from a project that was already bloated with files and I didn't feel to rewrite too much to get it working.. and now I'm too lazy to rewrite this solution.

# app/views/layouts/application.html.erb
# in <head>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= yield :stylesheets %>
<%= javascript_include_tag "application" %>
<%= yield :javascripts %>
# app/views/pages/index.html.erb
<% content_for :javascripts do %>
<% javascript_include_tag "pages_c" %>
<% end %>
<% content_for :stylesheets do %>
<% stylesheet_link_tag "pages_c %>
<% end %>
<div>
....
</div>
// app/assets/stylesheets/pages_c.css.scss
/*
*= depend_on colors
*=
*= require slideshow
*= require fonts
*= require grid_system
*/
.normal_scss_class {
}
# config/environments/production.rb
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile << /.+?_c\.(css|js)/ # Compile all js and css files that ends with "_c"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment